This entry is part 4 of 4 in the Unit Tests for WordPress Plugins Series
- Unit Tests for WordPress Plugins – An Introduction
- Unit Tests for WordPress Plugins – Setting Up Our Testing Suite
- Unit Tests for WordPress Plugins – Writing Tests
- Unit Tests for WordPress Plugins – The Factory
For many plugins, writing adequate unit tests requires the creation of sample post, user, taxonomy, and other data inside of the test WordPress install. While the standard WordPress functions for creating data, such as wp_insert_post(), work just fine, WordPress provides a set helper classes called WP_UnitTest_Factory that make it exceptionally simple.
The WP_UnitTest_Factory class is actually a wrapper for object type specific factory classes that each extend an abstract class called WP_UnitTest_Factory_For_Thing. If you look at the __construct() for WP_UnitTest_Factory, you will see that each object type is set up as a property of the class and holds an instance of the appropriate “thing” class:
These “thing” classes can be used to create, update, and retrieve data for each object type. The following methods are available for each:
- create_object( $args )
- update_object( $args )
- create( $args = array(), $generation_definitions = null )
- create_and_get( $args = array(), $generation_definitions = null )
- create_many( $count, $args = array(), $generation_definitions = null )
With these methods, creating sample data is really simple. Let’s take a look at a few examples.
Creating a Sample Post
To create a simple post, simply call the create() method with a few basic args:
$p = $this->factory->post->create( array( 'post_title' => 'Test Post' ) );
The ID of the post will be returned.
You can now use this to test against. For example, if you want to write a test that checks if searching works, you might have something like this: