PHPUnit:找出标头的发送位置


PHPUnit: Find out where the headers has been sent

我有一段代码正在使用 PHPUnit 进行测试,但收到以下错误:

session_regenerate_id(): Cannot regenerate session id - headers already sent

我想知道标头的发送位置;通常,当我在浏览器中测试代码时,我会看到一条警告,其中提到了如下所示的位置:

Warning: Cannot modify header information - headers already sent by 
(output started at /www/xxxx/x.php:52) in /www/xxxx/index.php on line 123

但是在 PHPUnit 测试中,没有这样的信息;PHPUnit 仅显示上述错误和回溯:

/var/www/yii/framework/web/CHttpSession.php:166
/var/www/yii/framework/web/auth/CWebUser.php:681
/var/www/yii/framework/web/auth/CWebUser.php:214
...

这只是指向错误发生的位置。

我能做什么?

它告诉您标头的发送位置。
解决方案是在测试函数中模拟会话组件。

$mockSession = $this->getMock('CHttpSession', array('regenerateID'));  
Yii::app()->setComponent('session', $mockSession);

我遇到了同样的错误,但我不使用 Yii。以下是我如何使用ob_*函数解决它:

我使用了一个phpunit.xml配置文件,其中提到了一个引导程序文件:

<phpunit bootstrap="phpunit_bootstrap.php">
    ...
</phpunit>

phpunit_bootstrap.php年,我开始使用ob_start()

<?php
ob_start();
// some other configuration lines ...

然后我在测试类中使用了 2 个 PHPUnit 方法:

// Erase output buffer before starting the tests
public static function setUpBeforeClass(){
    ob_clean();
}
// Turn off output buffering after the tests
public static function tearDownAfterClass(){
    ob_end_clean();
}

  • ob_clean()
  • ob_end_clean()
  • setUpBeforeClass() & tearDownAfterClass()