問題描述

在最新版本中,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 the factory member variable. The factory 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 to 0). 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。