Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhpUnit: Custom error messages while testing for method invocation

Tags:

php

phpunit

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?

like image 631
tampe125 Avatar asked Nov 15 '14 09:11

tampe125


1 Answers

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

like image 148
Fabian Schmengler Avatar answered Nov 08 '22 00:11

Fabian Schmengler