Wordpress - How do I mock HTTP requests for PHPUnit?

If you take a look at WP_HTTP->request() (which all related functions wrap) it provides a filter hook for the purpose of overriding making a request in favor of returning arbitrary data as response:

// Allow plugins to short-circuit the request
$pre = apply_filters( 'pre_http_request', false, $r, $url );
if ( false !== $pre )
    return $pre;

Take the results you get from a valid or invalid request, serialize them into strings, then add code that unserializes the string back into the variable instead of doing the request.


In order to isolate your code further, I would wrap the wp_remote_get etc calls in an interface with two implementations. One implementation calls wp_remote_get, and the other returns test data.

Using a tool such as runkit in this situation sidesteps the actual problem you have, which is that your code and the APIs are too tightly coupled, and a level of encapsulation and abstraction would be beneficial.