簡體   English   中英

單元測試的概念,是否應該將這些斷言拆分為“單元”?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM