“标头已发送"PHPUnit 测试期间返回错误 [英] "headers already sent" Error returned during PHPUnit tests

查看:17
本文介绍了“标头已发送"PHPUnit 测试期间返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PHPUnit 测试一套 REST Web 服务.我们使用输出缓冲来对响应进行 gzip 编码.当我使用 PHPUnit 对服务进行测试时,出现错误:

I'm testing a suite of REST web services with PHPUnit. We're using output buffering in order to gzip-encode the responses. When I run a test for the service with PHPUnit, I'm getting the error:

Cannot modify header information - headers already sent by (output started at /home/dotcloud/php-env/share/php/PHPUnit/Util/Printer.php:172)

抱怨我的代码回显是浏览器的输出...

It's complaining at the point that my code echo's the output to the browser...

我可以通过在测试类的顶部添加一个 ob_start() 调用来临时解决这个问题,但是当我一次运行多个测试时,我再次收到此错误.

I was able to work around this temporarily by adding an ob_start() call at the top of the test class(es), but when I run multiple tests at once, I get this error again.

有什么想法吗?

推荐答案

有几种不同的优缺点:

  1. 您已经发现,使用 @runInSeparateProcess 在单独的进程中运行测试.好: 更好的测试隔离,坏: 较差的性能,不能很好地与全局常量配合使用
  2. 使用 --stderr 标志将 PHPUnit 输出定向到 STDERR.好: 测试按预期工作,无需更改,坏: 感觉像是一个肮脏的解决方法,可能是 CI 工具的问题
  3. 实际上并不发送标头.将使用 header() 的类替换为存根,或者如果这不容易实现,或者您想要进行完整的功能测试,请模拟 header() 函数本身.this answer 中有关模拟内置函数的更多信息.好:您也可以测试标头的内容,您的测试对全局状态的依赖较少不好:您需要编写更多测试代码
  1. run the tests in separate processes with @runInSeparateProcess, as you already found out. Good: better test isolation, Bad: worse performance, does not work well with global constants
  2. use --stderr flag to direct PHPUnit output to STDERR. Good: tests work as expected without changes, Bad: feels like a dirty workaround, possibly problems with CI tools
  3. don't actually send headers. Either replace the classes that use header() with stubs or if this is not easily possible or you want to do a full functional test, mock the header() function itself. More info on mocking built-in functions in this answer. Good: you can test the contents of the headers as well, your tests do rely less on global state Bad: You'll need to write more test code

我会选择 (3),并且可能还会重构代码以拥有一个负责标头并且可以轻松模拟的单个类.

I'd go for (3) and probably refactor the code as well to have a single class that's responsible for the headers and can be easily mocked.

这篇关于“标头已发送"PHPUnit 测试期间返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆