gpt4 book ai didi

php - 单元测试概念,这些断言应该拆分为 "unit"吗?

转载 作者:行者123 更新时间:2023-11-28 21:02:55 25 4
gpt4 key购买 nike

尽管我玩了一段时间单元测试,但我无法真正理解“单元”的概念,即单一功能。

比如我正在测试一组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();

在一个测试中,并对这个对象执行多个断言。这似乎不无道理。

如果您在一次测试中测试多个方法调用,我会更加担心。为什么 ?早期断言会中止测试并且不会对进一步的方法执行测试。 最好的意味着第二种方法没有被测试,最坏的它隐藏了第二次测试揭示的证据(该证据可以帮助确定第一个方法的原因或范围失败)

出于这个原因,我确实尽量避免在单元测试方法中使用过多的断言。检查空对象,然后检查(在同一个测试中)填充字段并不是不合理的。不过,我不会将这些断言链接在一起,而是希望有多个测试来测试同一个返回实体的不同功能。

一如既往,这里有一定程度的实用性。

关于php - 单元测试概念,这些断言应该拆分为 "unit"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13915099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com