I've asked this on IRC, Twitter, Slack — am utterly astonished by how difficult it is to locate the answer to this:

I have a bunch of plugin code that only runs when is_admin() returns true, i.e., when the user is looking at the admin panel.

How do I arrange a unit test such that it's in the admin context when the assertions are run?

  • 1
    try define( 'WP_ADMIN', true ); Nov 2, 2015 at 15:33
  • @Scriptonomy frowns That's changing the underlying config of WordPress. Is this really how people are told to do it?
    – aendra
    Nov 2, 2015 at 15:46

1 Answer 1


According to this test, you use set_current_screen() to navigate to one of these in the setUp method.

Alas, none of this is apparent if you look at the tremendously-helpful reference page for get_current_screen()...


class AxisSetupTest extends WP_UnitTestCase {    
     * @covers AxisWP::__construct
    function test_constructor() {
        // Assert

        // Admin
        $this->assertInternalType('integer', has_action( 'admin_enqueue_scripts', array( 'AxisWP', 'add_admin_stylesheet' ) ) );

    public function setUp() {

            $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) );
            $user = wp_set_current_user( $user_id );

            // This is the key here.
            set_current_screen( 'edit-post' );

    public function tearDown() {
  • Worth noting that I eventually had to essentially instantiate the class and then call the methods manually anyway as the load order was funky and causing weird failures. The tl;dr is — don't bother testing any part of WordPress itself, instantiate your class manually and run your functions and assert output based upon that.
    – aendra
    Nov 2, 2015 at 18:11
  • 4
    Yes, I do essentially the same thing as this when the code being tested uses is_admin() or is_network_admin(). However, you might want to unset( $GLOBALS['current_screen'] ) in your tearDown() method (otherwise you could just remove it since it isn't needed if all it does is just call the parent method :-).
    – J.D.
    Nov 2, 2015 at 19:43

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.