2011-07-26 39 views

回答

7

你可以只保存了對於最終失敗,說有

$passing = true; 
if (! false) { $passing = false; } 
if (! true) { $passing = false; } 
$this->assertTrue($passing); 

,但我非常不鼓勵這種測試形式。我已經寫過這樣的測試,並且他們指數地失控,更糟的是,你開始因爲難以找到的原因而出現奇怪的失敗。

此外,比我更聰明的人同意,測試不應該有任何conditionals(if/else,try/catch),因爲每個條件都會增加測試的複雜性。如果需要一個條件,也許應該仔細查看測試和SUT或被測系統,以便使其更簡單。

更好的方法是將其更改爲兩個測試,如果它們共享設置的重要部分,則將這兩個測試移動到新的測試類中,並在Setup()中執行共享設置方法。

7

中,這可能會破壞單元測試的重點。您可能希望將其分解爲更多的測試方法,而不是採用單片測試方法。

這是一些僞代碼,作爲一個不好的例子。

MyBadTestMethod() 
{ 
    someResult = MyMethod(); 
    assertIsCorrect(someResult); 
    myResult2 = MyMethod2(someResult); 
    assertIsCorrect(myResult2); 
} 

MyMethod2 and myResult2 will fail。

這是一個更好的例子。

MyTestMethod1() 
{ 
    someResult = MyMethod(); 
    assertIsCorrect(someResult); 
} 
MyTestMethod2() 
{ 
    myResult2 = MyMethod2(someCorrectResult); 
    assertIsCorrect(myResult2); 
} 
+0

像OP一樣,我需要明顯的答案。默認情況下,PHPUnit會在測試失敗後繼續執行,而不是在單個測試中。 –

+0

@SethBattin所以這就是你需要的? –

+0

是的,謝謝。 –

10

其他回答者是正確的 - 如果你希望能夠做到這一點,你真的應該把你的斷言分解成單獨的測試。但是,假設您有合理的理由想要這樣做...有一種方法。

Phpunit聲明失敗實際上是異常,這意味着你可以自己捕捉並拋出它們。例如,你可以做個試驗:

public function testDemo() 
{ 
    $failures = []; 
    try { 
     $this->assertTrue(false); 
    } catch(PHPUnit_Framework_ExpectationFailedException $e) { 
     $failures[] = $e->getMessage(); 
    } 
    try { 
     $this->assertTrue(false); 
    } catch(PHPUnit_Framework_ExpectationFailedException $e) { 
     $failures[] = $e->getMessage(); 
    } 
    if(!empty($failures)) 
    { 
     throw new PHPUnit_Framework_ExpectationFailedException (
      count($failures)." assertions failed:\n\t".implode("\n\t", $failures) 
     ); 
    } 
} 

正如你所看到的,它會嘗試兩個斷言,它們都失敗了,但它等待,直到最後拋出的所有故障輸出消息作爲一個例外。