7

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 ); – Scriptonomy Nov 2 '15 at 15:33
  • @Scriptonomy frowns That's changing the underlying config of WordPress. Is this really how people are told to do it? – aendrew Nov 2 '15 at 15:46
10

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()...

Example:

<?php
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() {
            parent::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() {
            parent::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. – aendrew Nov 2 '15 at 18:11
  • 3
    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 '15 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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