在最新版本中WP_UnitTestCase
已包括$factory
所有物
例如:
$post = $this->factory->post->create();
在哪里可以找到有关此有用功能的文档?在最新版本中WP_UnitTestCase
已包括$factory
所有物
例如:
$post = $this->factory->post->create();
在哪里可以找到有关此有用功能的文档?据我所知,目前没有关于它的文件。这个official source is here.
我还写了一篇关于WordPress插件单元测试的教程,which gives some detail about this feature.
使用WP_UnitTestCase
是它的工厂。可以通过factory
成员变量。这个factory
是一个对象,其属性都是中定义的一个类的实例includes/factory.php. 你问他们做什么?它们使创建用户、帖子、术语等变得非常简单,只要您在测试中需要它们。因此,与其这样做,不如:
$args = array( /* A bunch of user data you had to make up */ );
wp_insert_user( $args );
您可以这样做:$user_id = $this->factory->user->create();
$user_ids = $this->factory->user->create_many( 25 );
这个factory
具有以下可以使用的属性:
$post
$attachment
$comment
$user
$term
$category
$tag
$blog
$user
工厂例如,您可以创建如下帖子:$this->factory->post->create();
post_author
字段将默认为0
). 有时,我们可能希望将帖子分配给用户。我们会这样做:$user_id = $this->factory->user->create();
$post_id = $this->factory->post->create( array( \'post_author\' => $user_id ) );
此外,如果您需要的不仅仅是正在创建的对象的ID,您不需要这样做:$post_id = $this->factory->post->create();
$post = get_post( $post_id );
相反,请使用create_and_get()
方法:// $post will be an instance of WP_Post
$post = $this->factory->post->create_and_get();
在本例中,我们使用post
工厂,但所有工厂都是如此。我想我会向WordPress文档团队提及这一点。也许我们可以把这些东西放到插件和主题手册中。
Update (June 20, 2015): 您还可以create your own custom factories!
Update (September 27, 2016): 在WordPress 4.4中tests were updated to provide a static factory()
method 用于访问工厂,尽管factory
属性仍然通过magic getter提供。