我正在尝试使用 PHPunit 来测试一个输出一些自定义 header 的类。
问题是在我的机器上是这样的:
<?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 内部的东西导致了这种情况?
问题可能是什么?
最佳答案
问题是 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');
}
关于php - 使用 PHPUnit 测试 PHP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9745080/