【发布时间】:2012-12-17 13:28:11
【问题描述】:
尽管我玩了一段时间的单元测试,但我无法真正理解“单元”的概念,即单一功能。
比如我在测试一组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);
}
【问题讨论】:
-
据我所知,“单元测试”中的“单元”是指测试“单元”(作为类和方法)作为测试整个应用程序的对比。因此,“单元”不需要您将其拆分为 3 个方法,而只是要求您在一般情况下隔离测试。
-
@zerkms 好的,那么您认为每个方法制作多个断言是否可以?
-
我认为它没有任何问题(我的想法基于我的个人经历和我所读过的内容)。实际上我会以完全相同的方式编写它。
-
尽可能多地,我倾向于每种测试方法都使用一种测试方法。
标签: php unit-testing testing phpunit