如何表明PHPUnit测试预计会失败?

时间:2010-10-12 18:41:44

标签: php unit-testing tdd phpunit

是否可以使用PHPUnit将测试标记为“预期失败”?这在执行TDD时很有用,并且您希望区分真正失败的测试,以及由于尚未编写相关代码而导致失败的测试。

6 个答案:

答案 0 :(得分:24)

我认为在这些情况下,简单地将测试标记为跳过是相当标准的。您的测试仍将运行且套件将通过,但测试运行器将提醒您跳过的测试。

http://phpunit.de/manual/current/en/incomplete-and-skipped-tests.html

答案 1 :(得分:11)

处理此问题的“正确”方法是使用$this->markTestIncomplete()。这将标记测试不完整。它会在返回时返回,但会显示提供的消息。有关详细信息,请参阅http://www.phpunit.de/manual/3.0/en/incomplete-and-skipped-tests.html

答案 2 :(得分:9)

我认为这是一个不好的做法,但你可以用这种方式欺骗PHPUnit:

/**
 * This test will succeed !!!
 * @expectedException PHPUnit_Framework_ExpectationFailedException
 */
public function testSucceed()
{
    $this->assertTrue(false);
}

更干净:

  public function testFailingTest() {  
    try {  
      $this->assertTrue(false);  
    } catch (PHPUnit_Framework_ExpectationFailedException $ex) {  
      // As expected the assertion failed, silently return  
      return;  
    }  
    // The assertion did not fail, make the test fail  
    $this->fail('This test did not fail as expected');  
  }

答案 3 :(得分:1)

如果您希望测试失败,但知道其失败是预期的,那么您可以在结果中输出add a message to the assertion

public function testExpectedToFail()
{    
    $this->assertTrue(FALSE, 'I knew this would happen!');
}

在结果中:

There was 1 failure:

1) testExpectedToFail(ClassTest)
I knew this would happen!

答案 4 :(得分:1)

上述六十九条的评论几乎完全适合我所寻找的内容。

当您为预期的异常设置测试时,fail()方法非常有用,如果它没有触发异常,您希望测试失败。

$this->object->triggerException();
$this->fail('The above statement was expected to trigger and exception.');

当然,triggerException会被对象中的某些内容替换。

答案 5 :(得分:0)

在PHPUnit 8.2.5中,您可以简单地预期抛出的断言异常:

$this->expectException('PHPUnit\Framework\ExpectationFailedException');
$this->assertTrue(false);