Configuration
After installing WP_Mock you will need to perform some simple configuration steps before you can start using it in your tests.
Bootstrap WP_Mock
Before you can start using WP_Mock to test your code, you'll need to bootstrap the library by creating a bootstrap.php file.
Here is an example of a bootstrap you might use:
The bootstrap file can do a few things:
Bootstraps the main WP_Mock handler which defines action and filter functions, as well as common WordPress constants
Sets up Patchwork if it has been turned on (see below)
Includes any custom files you need to run the test (optional)
Configure PHPUnit with WP_Mock
You can run PHPUnit using a --bootstrap
flag to include your bootstrap configuration while executing your tests (see PHPUnit documentation):
A more convenient way though would be to add the following to the phpunit.xml configuration file (see PHPUnit documentation):
Enable Patchwork
Patchwork is a library that enables temporarily overwriting user-defined functions and static methods. This means you can better isolate your system under test by mocking your plugin's functions that are tested elsewhere. If Patchwork is turned on, WP_Mock will transparently use it behind the scenes. For most use cases, you won't need to worry about using it directly.
If you'd like to use Patchwork in your tests, you need to specifically turn it on before bootstrapping WP_Mock:
Enable Strict Mode
WP_Mock has a strict mode that developers may optionally enable. By default, it is disabled. If enabled, strict mode will cause tests to fail if they use previously mocked functions without first explicitly declaring an expectation for how that function will be used. This provides an easy way to enforce an extra layer of specificity in unit tests.
Like using patchwork, strict mode has to be enabled before the WP_Mock framework is bootstrapped:
Extend WP_Mock Test Case
Once you have followed the configuration steps as outlined above, you'll want to update your test classes to extend the WP_Mock\Tools\TestCase
class for the best results when using WP_Mock. This class extends PHPUnit's own TestCase
class, with some helper and other methods that help WP_Mock to function properly.
If you do not wish to extend WP_Mock own test case, then you should make sure to call WP_Mock::setUp()
and WP_Mock::tearDown()
in your test case's setUp()
and tearDown()
methods respectively. This is not recommended though.
Last updated