2

For our PHPUnit testing, we sometimes write custom assertions. Today I found a custom assertion that wasn't asserting quite what it ought to have been. It seems that this problem could have been avoided if I had written a unit test for the assertion itself.

The only problem I see is that I'm not quite sure how to handle writing tests for an assertion that it ought to fail, without having that lead to the test itself failing. In other words, for a test that expects a string, 'foo', I want to do something like:

public function testAssertFoo()
{
   $var = 'bar';
   $callable = array( $this, "assertFoo" );
   $this->assertTestFails( $callable, $var );
}

Of course, there is no assertTestFails assertion. But is there a clean way to do something like that?

1 Answer 1

2

Assuming that assertFoo uses PHPUnit's built-in assertions such as assertEquals, you can simply catch the PHPUnit_Framework_ExpectationFailedException that is thrown when the assertion fails.

function testAssertFoo() {
    try {
        $this->assertFoo('bar');
        self::fail("assertFoo should fail for 'bar'");
    }
    catch (PHPUnit_Framework_ExpectationFailedException $e) { /* test passed */ }
}

function assertFoo($value) {
    self::assertEquals('foo', $value);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I didn't know about the PHPUnit_Framework_ExpectationFailedException. That should do it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.