鍍金池/ 問(wèn)答/PHP  測(cè)試/ PHPUnit 測(cè)試中包含sesssion怎么處理?

PHPUnit 測(cè)試中包含sesssion怎么處理?

問(wèn)題描述
使用PHPUnit測(cè)試一個(gè)方法,該方法中用到了session,然后報(bào)錯(cuò),要先開(kāi)啟session,請(qǐng)問(wèn)在phpunit中如何開(kāi)啟session

被測(cè)方法如下:

    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;
    }

測(cè)試方法如下:

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

運(yùn)行phpunit報(bào)錯(cuò)信息如下:

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有一個(gè)bootstrap的參數(shù)(同樣可以寫(xiě)到phpunit.xml配置文件中),可以指定在測(cè)試前預(yù)加載一些環(huán)境(比如開(kāi)啟session之類(lèi)的)

不過(guò)在cli下開(kāi)啟session沒(méi)什么用吧。而且你這個(gè)類(lèi)對(duì)session有依賴(lài),建議最好用mock的方式來(lái)解決

2017年11月10日 16:37