Cannot send session cookie - headers already sent PHPUnit / Laravel

◇◆丶佛笑我妖孽 提交于 2019-12-06 19:43:51

问题


I have this strange problem when i call the parent::setUp() on my TestCase class for unit test a class when i run phpunit it throw me this error:

1) MatchRequestRepositoryTest::test_find_requests_by_match_id ErrorException: session_start(): Cannot send session cookie - headers already sent by (output started at /var/www/project.dev/vendor/phpunit/phpunit/PHPUnit/TextUI/TestRunner.php:459)

What can be the problem? Thanks for any help.


回答1:


(UPDATE: Thanks to comment by Louis Charette, this will only work in php 7.1 and earlier (and reading the bug report, it sounds like a regression they don't intend to fix. The better solution is therefore Jeff Puckett's (https://stackoverflow.com/a/38045422/841830), of giving the --stderr flag on the commandline to phpunit. This keeps stdout for your code, stderr for phpunit, and so they don't clash.)


The problem is that you have some code, perhaps deep in the framework you use, that calls session_start(). That, in turn, wants to send a cookie. But PHPUnit has already started writing output to stdout.

The point to understand here is that this is just a unit test, no-one cares about the header. So just suppress the error message. And the way you do that, without altering the system-under-test, is to call session_start() in your own unit test (either before parent::setUp() or inside that setUp function). And use the @ prefix to suppress errors. e.g.

function setUp() {
  @session_start();
  parent::setUp();
  ...
}



回答2:


One way to handle this in PHPUnit is to send output to stderr instead of stdout as is demonstrated by this answer.

phpunit --stderr

Or by adding stderr="true" in your phpunit.xml as is pointed out in this comment.




回答3:


In Laravel I avoided the issue by checking the environment and avoiding problematic code for 'testing' environment.

// Code working in Laravel 4.2
if(App::environment() != 'testing') {
        // this will be skipped when testing
        setcookie('key', $val, time() + (86400 * 999), '/');
}

NOTE - Warning: this means you cannot test this piece of code!



来源:https://stackoverflow.com/questions/23270650/cannot-send-session-cookie-headers-already-sent-phpunit-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!