我有一个测试下面的测试方法,如果一个构造器正常工作:什么是单元测试构造函数的最佳方法?
选项#1
public function testConstructWorksProperly()
{
$id = 1;
$name = 'name';
$foo = new Foo($id, $name);
$this->assertEquals($id, $foo->getId());
$this->assertEquals($name, $foo->getNome());
}
选项#2
public function testConstructWorksProperly()
{
$id = 1;
$name = 'name';
$foo = new Foo($id, $name);
$this->assertAttributeEquals($id, 'id', $foo);
$this->assertAttributeEquals($name, 'name', $foo);
}
在选项#1我需要创建getter来声明构造函数正常工作,而在#2选项中,我使用断言来检查构造函数是否设置了p性能正确。
我总是想知道在每次使用选项#1时我需要公开访问这些属性,因为我节省了时间和LOC,而不是为getId
和getName
编写另外2个测试。
使用方案二似乎是一个白盒测试。 但是...
有一种说法:“每个测试一个断言”,所以,如果我的构造函数有6个参数,我需要6个断言和6个getter来公开测试这些方法。
你会使用哪个选项?
除了选项,也许它只是我,我会通过参数 – Andrew
@Andrew通过Foo'的'实例,我在测试Foo方法时,不要将它用作参数。 –
除非你的setters正在做一些与众不同的事情,单元测试getter和setter没有多大意义 –