

Mocking means that you overwrite the behavior of a function, making it much easier to test. For now, we will mitigate this problem by moving the function that returns a random value to a separate protected function so we can mock it. This also poses our first issue: Randomness is not something we can test.
Phpunit mocks code#
Adjusting your application's code to enhance the testing capability All it does is display a random song lyric in the top right of your admin, but it showcases WordPress' easy extensibility. This code is based on WordPress' own plugin, called Hello Dolly. "Du hast mich gefragt und ich hab nichts gesagt", Writing your code object-oriented provides a lot of benefits when writing your unit-tests. It is actually class-based and initialized in the plugin's main file. Let us now explore what it is we will be testing. It contains the initial source code (hello-rammstein-1-initial-project) and the finished source code (hello-rammstein-2-first-test). You can follow along with this tutorial using this project. If you are worried about using syntax or functionality your plugin's minimum required PHP version doesn't support, you can use tools like PHPCS to catch these. If your plugin supports an earlier version of PHP, don't worry, you can still run your unit-tests with a newer version of PHP. Note: For the writing of this post, I used PHPUnit 8 since it's the latest available version and uses a requires a PHP version that is still supported for a long time. This means installing PHPUnit in your WordPress plugin directory (or globally), installing BrainMonkey and Mockery, setting up a unit-tests folder, and so forth. Setting up the projectįirst, you shape the environment you want your code to live in.

The very definition of a unit test is that it runs in a sandbox where you, as the developer, control every aspect of what is going on outside of the piece of code you want to test. Running one test could affect another if we didn't revert everything back to the way it was and I won't have to tell you this is not what you want. But, you can teach your mock object to return different values. or maybe zero or an empty string, depending on the return type of the function. They depended on a fully-fledged WordPress environment, database and all. When you create a mock object, by default, PHPUnit overrides all of its methods and makes each return null. Together these tools can be a powerful tool to ensure the technical quality of your plugin.īefore we started using these tools at Yoast, our “unit”-tests were technically integration tests.

In this post, we will be covering the following tools: PHPUnit, Mockery and BrainMonkey. Luckily there are tools out there making it a lot easier. Unit-testing your WordPress plugin can be challenging.
