WordPress后端的单元测试(is_admin()为真)

时间:2015-11-02 作者:aendra

我在IRC、推特、Slack上问过这个问题,我对找到这个问题的答案有多困难感到非常惊讶:

我有一堆插件代码,只有在is_admin() 退货true, i、 例如,当用户查看管理面板时。

我如何安排单元测试,使其在运行断言时处于管理上下文中?

1 个回复
SO网友:aendra

根据this test, 您使用set_current_screen() 导航到one of thesesetUp 方法

唉,如果您查看非常有用的参考页get_current_screen()...

示例:

<?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();
    }
}