问题描述
使用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();
// 测试无效的参数
$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的参数(同样可以写到phpunit.xml配置文件中),可以指定在测试前预加载一些环境(比如开启session之类的)
不过在cli下开启session没什么用吧。而且你这个类对session有依赖,建议最好用mock的方式来解决