WordPress is often said to be a kind of Wild West for unit testing because it is not ‘object oriented enough.’ And yet, there are plenty of tools around to effectively test a WordPress installation, along with WordPress themes and plugins.
PHPUnit is a testing framework for PHP that can serve as the foundation of our unit testing.
Now that we have PHPUnit installed, let’s configure WP-CLI, a command line interface for WordPress. Installation instructions are on the front page of the WP-CLI site. The tools I will be detailing below depend on WP-CLI for their functionality.
These tests extend the PHPUnit test classes with special WordPress specific functionality. Installation instructions are here.
Here is the source code for the factory class. In lieu of official documentation, we can simply examine the code to see how it works.
$user_id = $this->factory->user->create( array( 'post_author' => $user_id ) );
What Should I Test My Theme For?
Every time I write an object, method, class, or function in my code, I am first going to write a test for it. Yes, the test will fail because I have written it before even writing the code I am testing. That is good because now I will write the code that “answers” the test with the correct functionality. In a 1-2 step, I will be writing both the test and another portion of my web application. This completes work on the project today, and it provides ongoing testing capabilities long after I have moved on to other development.
This means our development is test driven. We are “driving” our programming with tests by creating the tests first and then writing code to ensure that the tests pass.