WordPress testing tools
The sole ability to mocking functions is a great help on testing WordPress code.
All WordPress functions can be mocked and tested using the techniques described in the PHP Functions section, they are PHP functions, after all.
However, to test WordPress code in isolation, without a bunch of bootstrap code for every test, a more fine grained control of plugin API functions is required.
This is exactly what Brain Monkey offers.
Following functions are defined by Brain Monkey when it is loaded for tests:
If your code uses any of these functions, and very likely it does, you don't need to define (or mock) them to avoid fatal errors during tests.
Note that the returning value of those functions (most of the times) will work out of the box as you might expect.
For example, if your code contains:
// something in the middle
$did = did_action('my_custom_action');
the value of
$didwill be correctly
did_action()in WordPress returns the number an action was done).
Or if your code contains:
$post = [ 'post_title' => 'My Title' ];
$title = apply_filters('the_title', $post['post_title']);
the value of
'My Title', without the need of any intervention.
This works as long as there's no code that actually adds filters to
"the_title"hook, so we expect that the title stay unchanged. And that's what happen.
If in the code under test there's something that adds filters (i.e. calls
add_filter), the Brain Monkey version of
apply_filterswill still return the value unchanged, but will allow to test that
apply_filtershas been called, how many times, with which callbacks and arguments are used.
More generally, with regards to the WP hook API, Brain Monkey allows to:
- test if an action or a filter has been added, how many times that happen and with which arguments
- test if an action or a filter has been fired, how many times that happen and with which arguments
- perform some callback when an action is fired, being able to access passed arguments
- perform some callback when an filter is applied, being able to access passed arguments and to return specific values
And it does that using its straightforward and human-readable syntax.