我正在尝试使用PHPunit来测试一个输出一些自定义标头的类。
问题是在我的机器上是这样的:
<?php
class HeadersTest extends PHPUnit_Framework_TestCase {
public function testHeaders()
{
ob_start();
header('Location: foo');
$headers_list = headers_list();
header_remove();
ob_clean();
$this->assertContains('Location: foo', $headers_list);
}
}
或者甚至是这样:
<?php
class HeadersTest extends PHPUnit_Framework_TestCase {
public function testHeaders()
{
ob_start();
header('Location: foo');
header_remove();
ob_clean();
}
}
返回此错误:
name@host [~/test]# phpunit --verbose HeadersTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.
E
Time: 0 seconds, Memory: 2.25Mb
There was 1 error:
1) HeadersTest::testHeaders
Cannot modify header information - headers already sent by (output started at /usr/local/lib/php/PHPUnit/Util/Printer.php:173)
/test/HeadersTest.php:9
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
这看起来像是在测试运行之前向终端输出了其他内容,即使在PHP标记的开头之前没有包含其他文件,也没有其他字符。会不会是PHPunit内部的某些东西导致了这种情况?
问题可能是什么?
发布于 2012-03-17 08:36:59
问题是PHPUnit会在屏幕上打印一个标题,此时你不能添加更多的标题。
解决办法是在一个独立的进程中运行测试。下面是一个例子
<?php
class FooTest extends PHPUnit_Framework_TestCase
{
/**
* @runInSeparateProcess
*/
public function testBar()
{
header('Location : http://foo.com');
}
}
这将导致:
$ phpunit FooTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.
.
Time: 1 second, Memory: 9.00Mb
OK (1 test, 0 assertions)
关键是@runInSeparateProcess注释。
如果您使用的是PHPUnit ~4.1或更高版本,并收到以下错误:
PHP Fatal error: Uncaught Error: Class 'PHPUnit_Util_Configuration' not found in -:378
Stack trace:
#0 {main}
thrown in - on line 378
Fatal error: Uncaught Error: Class 'PHPUnit_Util_Configuration' not found in - on line 378
Error: Class 'PHPUnit_Util_Configuration' not found in - on line 378
Call Stack:
0.0013 582512 1. {main}() -:0
尝试将以下内容添加到您的引导程序文件中以修复它:
<?php
if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/path/to/composer/vendors/dir/autoload.php');
}
发布于 2012-05-30 20:03:43
尽管在单独的进程中运行测试确实解决了这个问题,但在运行大型测试套件时会产生明显的开销。
我的解决方法是将phpunit的输出定向到stderr,如下所示:
phpunit --stderr <options>
这应该会解决这个问题,而且这也意味着您不必创建包装器函数并替换代码中出现的所有内容。
发布于 2016-10-06 17:29:01
顺便说一句:对我来说,headers_list()
一直返回0个元素。我注意到了@titel对这个问题的评论,并认为它值得在这里特别提到:
只是想在其他人也对此感兴趣的情况下报道这一点。在运行PHPunit (使用PHP )时,
headers_list()
不起作用,但xdebug_get_headers()
起作用。
HTH
https://stackoverflow.com/questions/9745080
复制相似问题