[英]Unit testing concept, should these assertions be splitted to be “unit”?
尽管我在单元测试中玩了一段时间,但我并没有真正理解“单元”的概念,即单一功能。
例如,我正在测试一组newXxx
形式的魔术方法:
public function testMagicCreatorWithoutArgument()
{
$retobj = $this->hobj->newFoo();
// Test that magic method sets the attribute
$this->assertObjectHasAttribute('foo', $this->hobj);
$this->assertInstanceOf(get_class($this->hobj), $this->hobj->foo);
// Test returned $retobj type
$this->assertInstanceOf(get_class($this->hobj), $retobj);
$this->assertNotSame($this->hobj, $retobj);
// Test parent property in $retobj
$this->assertSame($this->hobj, $retobj->getParent());
}
如您所见,此测试方法中有三个断言的“组”。 为了遵循“单元测试”原则,是否应该将它们分为三种单一的测试方法?
拆分将类似于:
public function testMagicCreatorWithoutArgumentSetsTheProperty()
{
$this->hobj->newFoo();
$this->assertObjectHasAttribute('foo', $this->hobj);
$this->assertInstanceOf(get_class($this->hobj), $this->hobj->foo);
}
/**
* @depends testMagicCreatorWithoutArgumentReturnsNewInstance
*/
public function testMagicCreatorWithArgumentSetsParentProperty()
{
$retobj = $this->hobj->newFoo();
$this->assertSame($this->hobj, $retobj->getParent());
}
public function testMagicCreatorWithoutArgumentReturnsNewInstance()
{
$retobj = $this->hobj->newFoo();
$this->assertInstanceOf(get_class($this->hobj), $retobj);
$this->assertNotSame($this->hobj, $retobj);
}
您的测试方法正在对此进行测试:
$retobj = $this->hobj->newFoo();
在一个测试中,并对这个对象执行多个断言。 这似乎并不合理。
如果您要在一个测试中测试多个方法调用,我会更担心。 为什么呢 早期声明会中止测试,并且不会对其他方法执行测试。 最好的情况是未测试第二种方法,而最糟糕的是它隐藏了第二次测试所揭示的证据(该证据可帮助确定第一次失败的原因或范围)
因此,我确实尝试避免在单元测试方法中使用过多的断言。 检查一个空对象,然后检查(在同一测试中)一个填充字段并不是没有道理的。 不过,我不会将这些断言链接在一起,而是希望进行多个测试来测试同一返回实体的不同功能。
与以往一样,这里有一定程度的实用性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.