鍍金池/ 問答/PHP  測試/ PHPUnit 測試中包含sesssion怎么處理?

PHPUnit 測試中包含sesssion怎么處理?

問題描述
使用PHPUnit測試一個方法,該方法中用到了session,然后報錯,要先開啟session,請問在phpunit中如何開啟session

被測方法如下:

    public static function returnJson($arr = [], $type = 0)
    {
        $systemSession = new Zend_Session_Namespace('system');
        $arr['token']  = md5(time());//$systemSession->token;
        header("token: " . $systemSession->token);
        echo json_encode($arr, $type);
        exit;
    }

測試方法如下:

    public function testIsExist()
    {
        $sellerServ = new Application_Service_Api_Seller();
        // 測試無效的參數(shù)
        $paramsError = [
            'seller_id'   => 'A2UFATMAM9UT85',
            'customer_id' => 5633
        ];
        $this->assertEquals(true, $sellerServ->isExist($paramsError));
    }

運行phpunit報錯信息如下:

Time: 220 ms, Memory: 6.00MB

There was 1 error:

1) ApiSellerTest::testIsExist
Zend_Session_Exception: Session must be started before any output has been sent to the browser; output started in /home/feiffy/demo/KFB/vendor/phpunit/phpunit/src/Util/Printer.php/112

/path/library/Zend/Session.php:451
/path/library/Zend/Session/Namespace.php:143
/path/application/services/Util.php:236
/path/application/services/Util.php:337
/path/application/services/Api/Seller.php:102
/path/tests/apiSellerTest.php:73

ERRORS!
回答
編輯回答
未命名

phpunit有一個bootstrap的參數(shù)(同樣可以寫到phpunit.xml配置文件中),可以指定在測試前預加載一些環(huán)境(比如開啟session之類的)

不過在cli下開啟session沒什么用吧。而且你這個類對session有依賴,建議最好用mock的方式來解決

2017年11月10日 16:37