以下のようなテストをしたいときに便利。
- ショートコードが期待通りに発火する?
- the_contentなどのフィルターフックが発火してる?
テストの流れ。
- テスト用の投稿を保存
-
get_post()
で$postオブジェクトを取得する。 -
setup_postdata()
で現在のカレントの$post
にセットする。 -
the_content()
などのテンプレートタグの出力をテストする。
<?php
class Sample_Test extends WP_UnitTestCase
{
/**
* @test
*/
function sample_test()
{
$args = array(
'post_title' => 'Hello',
'post_author' => 1,
'post_content' => 'Hello World!',
'post_status' => 'publish',
'post_date' => '2014-01-01 00:00:00',
);
$this->setup_postdata( $args );
/*
* the_content()の結果に対してテスト
*/
$this->expectOutputString( "<p>Hello World!</p>\n" );
the_content();
}
/**
* Add post and post be set to current.
*
* @param array $args A hash array of the post object.
* @return none
*/
public function setup_postdata( $args )
{
global $post;
global $wp_query;
$wp_query->is_singular = true;
$post_id = $this->factory->post->create( $args );
$post = get_post( $post_id );
setup_postdata( $post );
}
}