2014-04-24 13:39 阅读 52

无法发送会话cookie - 标头已经发送过PHPUnit / Laravel

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/

What can be the problem? Thanks for any help.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    douqujin2767 douqujin2767 2014-05-01 01:42

    (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 (, 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() {
    点赞 评论 复制链接分享
  • doushengyou2617 doushengyou2617 2016-06-27 03:21

    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.

    点赞 评论 复制链接分享
  • dtmsaqtly798322992 dtmsaqtly798322992 2018-10-25 08:46

    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!

    点赞 评论 复制链接分享