Search code examples
phpmockingphpunitautomated-testserror-logging

How can I mock outputting messages to the error log with PHPUnit?


In this answer it mentions using expectOutputString() to, well, expect output strings in PHPUnit.

I also need to do sort of the counterpart of this, which is to tell a mock to output a string.

I was previously using $mock->will($this->throwException(Exception('foo')) to have my mock throw an exception but now instead of throwing an exception I need it to log the error and NOT re-throw the exception, which means I need my mock to output a string just as error_log() does in the method I'm trying to mock, so that my test can expect the string.

Does this make sense? Is it possible to do? Does PHPUnit offer a way to do it?


Solution

  • From the testability point of view, it's always better to abstract the error logging into a class. If you make direct calls to error_log() you will have difficulties checking the calls made.

    If you can't refactor your code and use a class for logging errors, you could try setting a custom error handler that will store the messages in some place, and then check those messages at the test, after the relevant call.

    But if you can, it's better to create a class with methods that abstract native php error logging. This class will be a dependency of the class under test. You can either pass it as a constructor mandatory argument, or have the class create it automatically, but allow to set it externally. Obviously, in the test you would inject a mock of that "ErrorLogger" class with expectations