2
votes

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

1 Answers

2
votes

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);
}