Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit:: How can function that set and get cookies, tested?

Tags:

php

phpunit

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

Example that give error:

PHPUnit_Framework_Error_Warning: Cannot modify header information - headers already sent by

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

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

like image 630
Ben Avatar asked Oct 11 '10 14:10

Ben


1 Answers

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).

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.

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)

like image 116
Core Xii Avatar answered Oct 04 '22 02:10

Core Xii