PHPUnit:如何设置和获取cookies,并进行测试?

时间:2021-07-17 01:59:32

PHPUnit:: How can function that set and get cookies, tested without get error : headers already sent by?

PHPUnit::如何设置和获取cookies,并在没有收到错误的情况下进行测试?

Example that give error:

例子给错误:

PHPUnit_Framework_Error_Warning: Cannot modify header information - headers already sent by

PHPUnit_Framework_Error_Warning:不能修改已经发送的头信息

MyCookie.php

MyCookie.php

class MyCookie{
public static function createCookie(){
        $uid = null;
        $cookieName='test_cookie';
        if(!isset($_COOKIE[$cookieName])){
            $uid = unique_hash();
            setcookie($cookieName, $uid, 0, '', '', false, true);
        }
        else{
            $uid=$_COOKIE[$cookieName];
        }
        return $uid;
    }
}

MyCookieTest.php

MyCookieTest.php

class MyCookieTest extends PHPUnit_Framework_TestCase{
    public function test_createCookie(){
            MyCookie::createCookie();
            assertThat(isset($_COOKIE['test_cookie']), is(true));
            unset($_COOKIE['test_cookie']);
            MyCookie::createCookie();
            assertThat(isset($_COOKIE['test_cookie']), is(true));
    }
}

Thanks

谢谢

1 个解决方案

#1


3  

If your PHP script does any output, the headers will be sent - And you cannot set cookies anymore. You have to send cookies first before you can output any HTML (or other output).

如果您的PHP脚本执行任何输出,头文件将被发送——并且您不能再设置cookie了。在输出任何HTML(或其他输出)之前,您必须先发送cookie。

If you're not outputting any HTML, then it's probably a whitespace somewhere accidentally being output, or the Unicode Byte-Order Mark. If your editor supports it, set it not to include the BOM in UTF-8 encoded files.

如果您没有输出任何HTML,那么很可能是输出的某个空格,或者是Unicode字节顺序标记。如果您的编辑器支持它,那么将它设置为在UTF-8编码文件中不包含BOM。

Finally, you may use the output buffering functions to delay the sending of any output until you've sent all your headers and set your cookies. (this will not fix accidental output before you begin buffering, though)

最后,您可以使用输出缓冲函数来延迟发送任何输出,直到您发送了所有的消息头并设置了cookie。(不过,这不会在开始缓冲之前修复意外输出)

#1


3  

If your PHP script does any output, the headers will be sent - And you cannot set cookies anymore. You have to send cookies first before you can output any HTML (or other output).

如果您的PHP脚本执行任何输出,头文件将被发送——并且您不能再设置cookie了。在输出任何HTML(或其他输出)之前,您必须先发送cookie。

If you're not outputting any HTML, then it's probably a whitespace somewhere accidentally being output, or the Unicode Byte-Order Mark. If your editor supports it, set it not to include the BOM in UTF-8 encoded files.

如果您没有输出任何HTML,那么很可能是输出的某个空格,或者是Unicode字节顺序标记。如果您的编辑器支持它,那么将它设置为在UTF-8编码文件中不包含BOM。

Finally, you may use the output buffering functions to delay the sending of any output until you've sent all your headers and set your cookies. (this will not fix accidental output before you begin buffering, though)

最后,您可以使用输出缓冲函数来延迟发送任何输出,直到您发送了所有的消息头并设置了cookie。(不过,这不会在开始缓冲之前修复意外输出)