Why Can’t PHPUnit UnitTest My WordPress Website

Unit tests for WordPress are a tricky thing. If you need to test the code with a live database, etc. I would suggest using the official WordPress test suite. I’ve gotten unit tests running for a plugin using that method before, but it wasn’t pretty, and was fairly unreliable. If you need to do it that way, though, I personally wouldn’t think of doing it with anything but the official test suite.

There’s tons of information on the official repository on the core make blog. In your test suite’s bootstrap file you need to set up any options that you need to override. Normally, that’s going to be active plugins (so you can test your plugin):

$GLOBALS['wp_tests_options'] = array(
  'active_plugins' => array( 'plugin-folder/plugin-file.php' ), // Relative to WP Plugin directory
);

After that, you need to include the includes/bootstrap.php file from the core test suite. Once that’s done, your tests ought to run as “expected”.

In my experience, however, those kinds of tests never run as expected, since the database and all of the WordPress code introduce an insane amount of hidden dependencies and state to your tests. Because of that, I prefer to just mock the WordPress api and run my tests without all those dependencies and all that state.

To do that, I use WP_Mock. It lets you simulate the WordPress environment with fine-grained control. For example, if you have a function that needs to add a filter to 'the_content' and then call the_content(), the following code for WP_Mock lets you test that:

WP_Mock::expectFilterAdded( 'the_content', 'some_callback_you_expect', 10, 2 );
WP_Mock::wpFunction( 'the_content', array(
  'times' => 1,
  'args'  => array(),
) );
your_function();

If the expectations set forth in WP_Mock are not met, it throws an exception, causing the test to fail.

Leave a Comment