77

Is there a more official way to force a phpunit failure than $this->assertTrue(false)?

3 Answers 3

125

I believe this should work within a test case:

$this->fail('Message');
5
  • 5
    The $this->fail() will stop the execution of the test, so this shouldn't be used as a replacement to assertions to display a message if you have multiple assertions in your test.
    – Prusprus
    Commented Sep 30, 2012 at 18:00
  • 2
    Passing an exception to fail will result in a nice stacktrace
    – Koen.
    Commented Sep 9, 2015 at 21:15
  • is there an opposite function of $this->fail()?
    – emfi
    Commented May 14, 2018 at 9:17
  • 3
    @emfi - yes, return;.
    – HappyDog
    Commented Aug 27, 2018 at 20:54
  • If you just return;, you will probably also need the @doesNotPerformAssertions annotation.
    – Nye
    Commented Dec 9, 2021 at 17:14
3

Yes, theres a way,

$this->fail("your message");

if you want to see the page u have failed than

print_r(getResponse()->getContent());
1
  • 4
    getResponse() is a framework specific function, which may not be generally available.
    – bishop
    Commented Aug 12, 2016 at 17:07
3

Another way to do it (especially helpful when writing a testing tool) would be:

use PHPUnit_Framework_ExpectationFailedException as PHPUnitException;

try {
    // something here
} catch (SpecificException $e) {
    // force a fail:
    throw new PHPUnitException("This was not expected.");
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.