4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPUnitでランダムなユーザーを登録して、そのユーザーをログインユーザーとしてセットする

Last updated at Posted at 2015-01-09

たとえばある関数を特定のロールのユーザーのみに許可したい場合に、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 );
	}
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?