使用PHPUnit测试PHP标头 [英] Test PHP headers with PHPUnit
问题描述
我正在尝试使用PHPunit测试一个输出一些自定义标头的类.
I'm trying to use PHPunit to test a class that outputs some custom headers.
问题是在我的机器上是这样:
The problem is that on my machine this:
<?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内部的某种原因导致了吗?
This looks as if there is something else outputting to the terminal before the test runs even though there is no other file included and there is no other character before the beginning of the PHP tag. Could it be something inside PHPunit that is causing this?
问题可能是什么?
推荐答案
问题是PHPUnit将在屏幕上显示标题,并且此时您无法添加更多标题.
The issue is that PHPUnit will print a header to the screen and at that point you can't add more headers.
解决方法是在独立的过程中运行测试.这是一个例子
The work around is to run the test in an isolated process. Here is an example
<?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批注.
The key is the @runInSeparateProcess annotation.
如果您使用的是PHPUnit〜4.1之类的东西,则会收到错误消息:
If you are using PHPUnit ~4.1 or something and get the error:
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
尝试将其添加到您的引导程序文件中以对其进行修复:
Try add this to your bootstrap file to fix it:
<?php
if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/path/to/composer/vendors/dir/autoload.php');
}
这篇关于使用PHPUnit测试PHP标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!