Cannot send session cookie - headers already sent PHPUnit / Laravel

前端 未结 4 1419
小蘑菇
小蘑菇 2021-02-19 22:50

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:

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-19 23:31

    (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();
      ...
    }
    

提交回复
热议问题