In recent versions WP_UnitTestCase has included a $factory property.
For example:
$post = $this->factory->post->create();
Where can I find documentation on this useful feature?
As far as I know, there is no documentation for it at present. The official source is here.
I have also written a tutorial on unit testing WordPress plugins, which gives some detail about this feature.
One of the advantages of using
WP_UnitTestCaseis its factories. These can be accessed through thefactorymember variable. Thefactoryis an object with properties that are each an instance of one of the classes defined in includes/factory.php. What do they do, you ask? They make it very simple to create users, posts, terms, etc., wherever you need them in your test. So, instead of doing this:$args = array( /* A bunch of user data you had to make up */ ); wp_insert_user( $args );You can just do this:
$user_id = $this->factory->user->create();But wait, it gets even better. What if you need many users (or posts, or whatever)? You can just create them in bulk like this:
$user_ids = $this->factory->user->create_many( 25 );That will create 25 users that you can use in your test.
The
factoryhas the following properties that you can use:
$post$attachment$comment$user$term$category$tag$blogThey may all be used in the same manner as demonstrated in the above example with the
$userfactory. For example, you can create a post like this:
$this->factory->post->create();You can also specify particular arguments to use for creating the object. In the above example we created a post, but it wasn't assigned to a particular user (the
post_authorfield will default to0). Sometimes we may want the post assigned to a user instead. We'd do that like this:$user_id = $this->factory->user->create(); $post_id = $this->factory->post->create( array( 'post_author' => $user_id ) );Also, if you need more than just the ID of the object you are creating, you don't need to do this:
$post_id = $this->factory->post->create(); $post = get_post( $post_id );Instead, use the
create_and_get()method:// $post will be an instance of WP_Post $post = $this->factory->post->create_and_get();In this example, we used the
postfactory, but the same is true for all of the factories.
I think I'll mention this to the WordPress docs team. Maybe we can get this stuff into the plugin and theme handbooks.
Update (June 20, 2015): You can also create your own custom factories!
Update (September 27, 2016): In WordPress 4.4 the tests were updated to provide a static factory() method for accessing the factories, although the factory property is still provided via a magic getter.
The source code at
https://github.com/rnagle/wordpress-unit-tests/blob/master/includes/factory.php
seems to be the best place to look at the moment