尽管我已经玩了一段时间的单元测试,但我无法真正理解“单元”的概念,这是一个单一的功能。
例如,我正在测试以下形式的一组魔术方法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);
}