8

Currently I am writing tests for a framework and we usually use a custom error message when a test fails, adding some useful info for debugging:

$this->assertEquals($check, $result, 
             'Class::method returned the wrong result with argument XXX');

However I'd wish to customize the error message while checking for function invocation:

$mock->expects($this->any())->method('foobar')->with($this->equals('dummy'));

When the above assertion is not true, I get the standard message.
I searched inside PhpUnit documentation, but I can't find a way to customize the error message, am I missing anything?

2 Answers 2

1

That's not intended but you can (ab)use the way, PHPUnit raises an expectation failure: it throws a PHPUnit_Framework_ExpectationFailedException.

So as long as these internals do not change1, you can use:

$mock->expects($this->any())->method('foobar')->with($this->equals('dummy'));
try {

   // your test code here

} catch (\PHPUnit_Framework_ExpectationFailedException $e) {
    $this->fail('your custom message here');
}

Note that if you have multiple expectations for the same test code, it's not that easy anymore, you would have to inspect $e->getMessage() and change your message accordingly. This is a level of verbosity (and source for errors) that I would not undertake just to change the messages which already are quite explanatory.


1) Current version of phpunit-mock-objects package: 3.0.6. See https://github.com/sebastianbergmann/phpunit-mock-objects/tree/3.0/src/Framework/MockObject/Matcher

0

Another option is to check the invocation information manually. Not sure how to check the parameters, but here is an example of checking the invocation count

$myMock = $this->getMockBuilder(MyClass::class)->getMock();
$matcher = $myMock ->expects($this->once())->method('myFunctionToCount')->getMatcher();
//execute code that calls myFunctionToCount on $myMock
$this->assertEquals(1, $matcher->invocationMatcher->getInvocationCount(), "Assertion message goes here");

This is sort of what the test runner is doing internally, but gives you control over the assertion message

It's not perfect as you need to keep the expects count and the assert count in sync

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