How to indicate that a PHPUnit test is expected to fail?
Is it possible to mark a test as "expected to fail" with PHPUnit? T开发者_运维知识库his would be useful when performing TDD, and you want to distinguish between genuinely failed tests, and tests that happen to fail because the associated code hasn't been written yet.
I think in these cases, it's fairly standard to simply mark the test as skipped. Your tests will still run and the suite will pass, but the test runner will alert you of the skipped tests.
http://phpunit.de/manual/current/en/incomplete-and-skipped-tests.html
The 'correct' method of handling this is to use $this->markTestIncomplete()
. This will mark the test as incomplete. It will come back as passed, but it will display the message provided. See http://www.phpunit.de/manual/3.0/en/incomplete-and-skipped-tests.html for more information.
I really think it's a bad practice, however you can trick PHPUnit this way:
/**
* This test will succeed !!!
* @expectedException PHPUnit_Framework_ExpectationFailedException
*/
public function testSucceed()
{
$this->assertTrue(false);
}
More cleanly:
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');
}
The comment by sixty-nine above is nearly perfect for what I was searching for.
The fail() method is useful for when you set a test for an expected exception and if it did not trigger the exception you want the test to fail.
$this->object->triggerException();
$this->fail('The above statement was expected to trigger and exception.');
Of course the triggerException is replaced by something in your object.
If you want to have a test fail but know that its failure was expected, you can add a message to the assertion that will output in the results:
public function testExpectedToFail()
{
$this->assertTrue(FALSE, 'I knew this would happen!');
}
In the results:
There was 1 failure:
1) testExpectedToFail(ClassTest)
I knew this would happen!
In PHPUnit 8.2.5 you can simply expect the thrown assertion exception:
$this->expectException('PHPUnit\Framework\ExpectationFailedException');
$this->assertTrue(false);
精彩评论