儘管我在單元測試中玩了一會兒,但我不能真正理解「單元」的概念,即單一功能。單元測試的概念,如果這些斷言被分解爲「單元」?
例如,我在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
@zerkms好吧,你認爲每個方法做出多個斷言是好的嗎? – gremo
我沒有看到任何問題(我根據我的個人經驗和我讀過的內容來思考)。其實我會用完全相同的方式寫出來。儘可能多地使用 – zerkms