Code Coverage problems

2009-11-10 17:47:37

I recently ran into a problem that stopped me from having 100% test coverage on a file. This is the piece of code, the overall reasoning for it can be found on the microtime manual page:

This function is only available on operating systems that support the gettimeofday() system call.

if (function_exists("microtime")) {
    $s = microtime(true);
} else {
    $s = time();

In case you did not spot it, the else path is never accessed if your system has a "microtime" function available. Additionally the change can be non-trivial because time() returns something like 1012314124 and microtime() returns "0.80057400 1257872321" or "1257872326.3036".

My first idea was something like this in the test case:

ini_set('disable_functions', 'microtime');

Then the idea was to use variable functions, but in the end I think it's not worth to change the source code to something less intelligable only to achieve 100% test coverage for a trivial case.

Of course you could always invoke a CLI php with a special php.ini if you have bigger chunks of code to be tested depending on the availability of certain functions.

Another idea could be to create a wrapper for microtime that you can mock and in your mock object always return the output of time() instead of microtime(), this would probably be the best tradeoff between readability and testability.

Any ideas?


Life's a bitch, life's a whore. Nothing less, nothing more.

Read More