How do I mock HTTP requests for PHPUnit?

I’m writing a plugin that makes requests to the Facebook graph API. As I don’t want my unit tests to actually make these requests, how would I overcome this? My method calls both wp_remote_get and wp_remote_post. Searching there does seem to be a way to mock functions using runkit, here

I want to avoid having contributers requiring too many dependencies so would like to avoid the above method. Is there any other options? My class extends the WP_UnitTestCase so I’m hoping maybe there’s something from the wp unit-tests that I could use?

5 s
5

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;

Leave a Comment