PHP Developer

My notes and thoughts about Linux, WordPress, PHP, WPML, Toolset and many more.

WP_Mock PHPUnit Testing Framework to WordPress Plugin: Complete Guide

Introduction

WP_Mock: ( https://github.com/10up/wp_mock ) is an API mocking framework that can be used for unit testing WordPress Plugins. This tutorial is a complete beginner guide to add and integrate WP_Mock mocking framework to your WordPress Plugin. WP_Mock uses Mockery PHP mock object framework for unit testing WordPress plugins. This is how to properly implement unit test inside WordPress plugins and can be considered as one of the best practices. If you are already familiar with mocking and unit testing, you can skip the introduction below and proceed directly to requirements and steps section.

Below are some introduction for beginners:

  • It allows developer to “mock” test data, objects, properties, classes and methods to be used during the testing. In short, you don’t need to rely on the WordPress core environment to be loaded just test your plugin. This minimize test time, complexity and improve efficiency of your tests. Other synonyms of “mock” as used with testing includes “fake”, “staged”, “planned” or “simulate”.
  • Since there is no loading of WordPress environment during this testing. It does not actually use real database or actual $wpdb object methods to read and transact testing data from database tables. Again this is mocked or simulated when using WP_Mock and Mockery.
  • All WordPress core functions are mocked as well. A common example is if you are getting post from a database using get_post() or retrieving users using get_users(). You are not actually calling these functions since WordPress is not loaded when using WP_Mock. You define and set this in advance before actually calling one of your plugin method that you need to test.
  • Since dependencies are mocked except with the method you are testing, you can be confident that the test pass or fail entirely depends on the “unit” being tested and not with the other dependencies.

This tutorial works best with a Linux environment such as Ubuntu. Also it assumes you will be using GitHub as your code repository manager to store your plugin. Although concepts can be applied to other UNIX based OS such as Mac or other git repository manager such as

Requirements

  • You should have git already installed. If this is the not case, you can simply install it with:

    You will use git to actually install your plugin WP_Mock library and its dependencies from GitHub.
  • You should have composer installed. In Ubuntu, you can install this easily by:

    Composer is used to install third party dependencies that is needed by WP_Mock such as Mockery, phpunit library, etc.
  • Latest phpunit library now requires at least PHP 7.0, so make sure you are using this version in your test environment. You can get the PHP version in the command line using: php --version. You should get at least PHP 7.0 on it:
  • You should be connected to the Internet when you integrate WP_Mock with your plugin. This is required to fetch all required third party libraries.

Plugin Structure

Assuming you have the following plugin structure:

You have a plugin folder called “wp-mock-test-demo“. Under this main plugin folder, you will find the main plugin file wp-mock-test-demo.php and the include folder where the plugin classes are stored.

The above structure is common to many plugin nowadays. Again that’s an example only and its simplified for the sake of this tutorial.

Steps

Now you have all the requirements set, below are the steps to integrate WP_Mock to the above example plugin.

  1. Create a composer.json file. Below are the contents of the composer.json file for the above test plugin:

    This composer.json should be located in your main plugin root directory. In the above plugin example, the resulting path of composer.json is /wp-content/plugins/wp-mock-test-demo/composer.json

    Explanation to the above composer.json settings:

    • name, description, authors should be self-explanatory. Just edit them and put your own values there.
    • 10up/wp_mock should point to dev-master, so you will always get the very latest WP_Mock releases
    • phpunit/phpunit should point to the very latest version. Currently (as of January 2018) its 6.5 and above. You should continually check the phpunit installation page and scroll down to “Composer” section to get the recommended version to use, e.g. screenshot:

      You can also check the phpunit release page in GitHub. Example, latest version (as of the time this tutorial is written is 6.5.5):
    • Under autoload -> classmap is where you will put the path of your plugin classes that you need to test. Example classmap has a value of includes/ because this is where the sample plugin classes are located. Composer will autoload these classes automatically for testing with phpunit.
  2. Create phpunit.xml. Please add this also under your main plugin root directory example at this path: /wp-content/plugins/wp-mock-test-demo/. The following is the code of phpunit.xml for the demo plugin under testing:

    phpunit.xml is the phpunit configuration file. Based on the above configuration, it tells the following information:

    • The bootstrap path is in unit-tests/bootstrap.php
    • Your test files should be found in unit-tests/tests

    You will be creating these files and directories later on. Take note that since this is a configuration file, it can be customized to fit your own test environment. (e.g. change the path names and test folders,etc.)

  3. According to your phpunit.xml, you should be creating a bootstrap.php file under a directory called unit-tests. Create this directory first and then add the bootstrap file inside it. This should be the code of your bootstrap file:

    The purpose of this script is to auto load the composer items that will be using for your testing. Your bootstrap.php should be found in: /wp-content/plugins/wp-mock-test-demo/unit-tests/. The script vendor/autoload.php will be automatically created when you finally install the test dependencies with composer later on.

  4. Also according to your phpunit.xml, you should be creating a tests directory under the unit-tests directory. So go ahead and create this tests directory. This is where you will put your unit test files later on.
  5. Now you are all set, next step to run composer to install all required dependencies. In the command line, run this command at your plugin root directory:

    The installation can take a while depending on your Internet connection. Wait until all is completed. This installation processes creates new directory called “vendor” and there are several sub-directories and files under it.

Now you are all set. This is how the demo plugin structure would look like after completing the above integration and installation of third party libraries for using with your tests.

Writing your first unit test

Once the above installation of the third party dependencies are done with composer. You are now ready to write your first unit test with WP_Mock! Let’s use the above example plugin in writing test. Supposing the plugin class class-wp-mock-demo-plugin.php contains the following code:

Based on the class code, there are two methods. The first method init_hooks is meant to initialize plugin hooks. The second method is the callback to the WordPress filter document_title_parts. The objective is to append login status to the title of the WordPress post or pages. Supposing you will test that these two methods works as intended. You will need to write two unit tests:

  • Test init_hooks method to ensure that it initialize hooks
  • Test append_login_status_to_title to ensure that it appends the text USER LOGGED-IN to the title tag when a user is logged-in

Finally to write your own unit test:

  1. Create a PHP file called test-wp-mock-demo-plugin.php and save it under unit-tests/tests
  2. Inside this test file, add this default code:

    This is your default WP_Mock test template file. Every time your add a new test file, start with this template. It consists of adding a basic setup and teardown of WP_Mock test.

  3. Now its time to add your actual tests. The following are the complete code of the tests:

Please read the code comments in the test for details. Explaining this is beyond the scope of this tutorial. For more information, please refer to these following documentations:

WP_Mock Basic Usage
PHPUnit Assertions

Running your unit test

To run the test, execute this at the terminal:

The test results will be shown like the one below:

Download the sample demo plugin

You can get the sample demo plugin used in this tutorial in GitHub: https://github.com/codex-m/wp-mock-test-demo

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">