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?
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:In one (two) word(s): Mock Data. PHPUnit got
getMock()
available exactly for that. As the other answers already have perfectly summoned……there only (might be) the issue left that your local SSL certificate verification might fail. WP ships with a filter for that:
For any further information about the WP HTTP API, you might want to dig into this answer, this answer, this answer by @Wyck and this answer by @toscho.
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 callswp_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.
I’ve had to mock WordPress’s HTTP request functions on a few occasions, and so I decided to build a tool for doing that: WP HTTP TestCase
Basically it provides an easy way to do the various things that the other answers have outlined. From the readme: