Is there any way to run a test on output created from a call to 'error_log("Message")' when doing unit tests with phpunit?
Example code, one of my functions tests a credit card with a luhn algorithm:
if($checkLuhn && ($this->_luhn_check($cardNumber) == false)) {
error_log(__METHOD__ . " cardNumber failed luhn algorithm check.");
return false;
}
$checkLuhn is a boolean passed in to tell it whether to do the check, the _luhn_check() returns true if the $cardNumber passes. Problem is, I have more than one test in this function that can return false. I can use assertEquals on the return value, but also want to check why the error was thrown.
Can you override error_log or otherwise grab syslog output in a unit test somehow?
PHPUnit is a framework independent library for unit testing PHP. Unit testing is a method by which small units of code are tested against expected results. Traditional testing tests an app as a whole meaning that individual components rarely get tested alone.
The assertSame() function is a builtin function in PHPUnit and is used to assert whether the actually obtained value is the same as the expected value or not. This assertion will return true in the case if the expected value is the same as the actual value else returns false.
PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.
How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.
There are a few different ways to direct where error_log() sends data.
First is to just as error_log() to send it some where else. An example would be:
error_log( 'This is a message from error_log()', 3, '/dev/stdout' );
That uses the destination option for error_log().
Another approach is to override the error_log ini setting in PHP. That would look something like:
$cur_error_log = ini_get( 'error_log' );
ini_set( 'error_log', '/dev/stdout' );
error_log( 'This is a message from error_log()' );
ini_set( 'error_log', $cur_error_log );
Of the two options I generally prefer using the destination option in error_log() when possible.
From there you could use expectOutputString() from PHPUnit to look for the data sent from error_log().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With