问题描述
在最新版本中,WP_UnitTestCase
已经包含了 $factory
属性。
例如:
$post = $this->factory->post->create();
在哪里可以找到有关此功能的文档?
最佳解决方案
据我所知,目前没有文件。 official source is here 。
我还写了一个单元测试 WordPress 插件,which gives some detail about this feature 的教程。
One of the advantages of using
WP_UnitTestCase
is its factories. These can be accessed through thefactory
member variable. Thefactory
is 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
factory
has the following properties that you can use:
$post
$attachment
$comment
$user
$term
$category
$tag
$blog
They may all be used in the same manner as demonstrated in the above example with the
$user
factory. 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_author
field 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
post
factory, but the same is true for all of the factories.
我想我会向 WordPress 文档小组提及。也许我们可以把这个东西放到插件和主题手册中。
更新 (2015 年 6 月 20 日):您也可以 create your own custom factories!
更新 (2016 年 9 月 27 日):在 WordPress 4.4 中,测试已更新,以提供静态 factory()
方法来访问工厂,尽管 factory
属性仍通过魔术吸气剂提供。
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。