たとえばある関数を特定のロールのユーザーのみに許可したい場合に、PHPUnitで任意のロールのユーザーを作成して、そのユーザーをカレントユーザーとして、テストを実行したい場合に使用する。
<?php
class SampleTest extends WP_UnitTestCase
{
/**
* @test
*/
public function sample_test()
{
// administratorを追加してカレントユーザーに。
$this->set_current_user( 'administrator' );
// switch_themesを実行できる
$this->assertTrue( current_user_can( 'switch_themes' ) );
// editorを追加してカレントユーザーに。
$this->set_current_user( 'editor' );
// switch_themesは実行できてはいけない。
$this->assertFalse( current_user_can( 'switch_themes' ) );
}
/**
* Add user and set the user as current user.
*
* @param string $role administrator, editor, author, contributor ...
* @return none
*/
public function set_current_user( $role )
{
$user = $this->factory()->user->create_and_get( array(
'role' => $role,
) );
/*
* Set $user as current user
*/
wp_set_current_user( $user->ID, $user->user_login );
}
}