【发布时间】:2011-04-24 11:49:04
【问题描述】:
是否可以使用 PHPUnit 将测试标记为“预期失败”?这在执行 TDD 时很有用,并且您想区分真正失败的测试和由于相关代码尚未编写而碰巧失败的测试。
【问题讨论】:
标签: php unit-testing tdd phpunit
是否可以使用 PHPUnit 将测试标记为“预期失败”?这在执行 TDD 时很有用,并且您想区分真正失败的测试和由于相关代码尚未编写而碰巧失败的测试。
【问题讨论】:
标签: php unit-testing tdd phpunit
我认为在这些情况下,简单地将测试标记为已跳过是相当标准的。您的测试仍将运行并且套件将通过,但测试运行程序会提醒您跳过的测试。
http://phpunit.de/manual/current/en/incomplete-and-skipped-tests.html
【讨论】:
I,最重要的是,如果测试通过,它应该会失败,因为这意味着我们忘记删除 TDD 标记。我不知道如何在 phpunit 中轻松做到这一点
如果您希望测试失败但知道它的失败是意料之中的,您可以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!
【讨论】:
我真的认为这是一个不好的做法,但是你可以这样欺骗 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');
}
【讨论】:
PHPUnit_Framework_AssertionFailedError,而不是PHPUnit_Framework_ExpectationFailedException
处理此问题的“正确”方法是使用$this->markTestIncomplete()。这会将测试标记为未完成。它会按过去返回,但会显示提供的消息。请参阅http://www.phpunit.de/manual/3.0/en/incomplete-and-skipped-tests.html 了解更多信息。
【讨论】:
markTestIncomplete 用于当您有一个“未实现的测试”时(phpunit.de/manual/3.7/en/incomplete-and-skipped-tests.html 首先描述了一个未实现的测试的空测试方法,然后解释了它如何导致错误的成功)。
上面 69 的评论对于我正在搜索的内容几乎是完美的。
fail() 方法在您为预期的异常设置测试并且如果它没有触发您希望测试失败的异常时很有用。
$this->object->triggerException();
$this->fail('The above statement was expected to trigger and exception.');
当然 triggerException 会被你的对象中的某些东西所取代。
【讨论】:
在 PHPUnit 8.2.5 中,您可以简单地期待抛出的断言异常:
$this->expectException('PHPUnit\Framework\ExpectationFailedException');
$this->assertTrue(false);
【讨论】: