Writing a unit test for add_menu_page

Rather than worrying about the internal implementation of the menu code and the globals that it uses (there are several beside $menu), I’d use a function like menu_page_url() to check if the page exists. That function will return the URL if the menu is registered, or an empty string if it is not. So you could do:

$this->assertNotEmpty( menu_page_url( 'my_menu_slug' ) );

Additionally, you are not setting up the test correctly. The go_to() method only sets up the main WP_Query object, it doesn’t work for admin URLs. You need to instead call your function that registers the admin menu. So your test would look something more like this:

class AdminTests extends WP_UnitTestCase {

    public function setUp() {

        parent::setUp();

        wp_set_current_user( self::factory()->user->create( [
            'role' => 'administrator',
        ] ) );
    }

    public function test_admin_menu() {

        my_admin_menu_registration_func();

        $this->assertNotEmpty( menu_page_url( 'my_menu_slug' ) );
    }

}

Leave a Comment