I want to test some methods in my plugin, and some of them required user to be logged in.

I searched everywhere but found nothing of use.

I need to test a method that takes in logged in session token from a user. For that, I need to mock logged user and then get his token using wp_get_session_token.

But I'm not sure how to do that.

class Test_Class extends WP_UnitTestCase {

   * Checks the error for invalid user token
   * @since 1.1.0
  public function test_add_app() {

    $user = $this->factory->user->create();

    wp_set_current_user( 1 );
    $auth_token  = wp_get_session_token();
    $auth_cookie = wp_parse_auth_cookie();

    // I'm checking for validity here but the token seems to be empty
    // so the test fails every time.

I've read that I can mock data with the factory provided by WP_UnitTestCase, but I'm not sure what I'm doing wrong.

1 Answer 1


Just few notes:

Looks like you're doing functional/integration tests rather than unit tests in isolation.

Here you're creating a user, but not setting it as the current one:

$user = $this->factory->user->create();
wp_set_current_user( 1 );

You probably want:

$user_id = $this->factory->user->create();
wp_set_current_user( $user_id );

Note that cookies aren't set here, because of:

tests_add_filter( 'send_auth_cookies', '__return_false' );

If you use e.g.

add_filter( 'send_auth_cookies', '__return_true' );

then you will get an error when setcookie() is called from wp_set_auth_cookie():

Cannot modify header information - headers already sent by (

The wp_get_session_token() is a wrapper of wp_parse_auth_cookie().

Parsing a cookie with wp_parse_auth_cookie assumes $_COOKIE is set.

Wonder if a fake token string would work in your tests?

Else one could try:

$expiration = time() + DAY_IN_SECONDS;
$manager    = WP_Session_Tokens::get_instance( $user_id );
$token      = $manager->create( $expiration );

with a verification:

$this->manager->verify( $token );

and then a cleanup:

$this->manager->destroy( $token );
  • Yeah, I meant integration test (for this case), I'm actually running unit test for other part, but that's not failing :D. The issue is that $this->factory->user->create() throws Undefined index: _wpnonce_create-user :S
    – dingo_d
    Commented Apr 13, 2018 at 12:55
  • And this error comes from the above Test_Class, even when $user = $this->factory->user->create(); is the only line in test_add_app() ?
    – birgire
    Commented Apr 13, 2018 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.