Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing cookies in PHP

The default practice for unit testing functionality that relies on session/cookie information is to use an abstraction library. But what if I want to write and unit test this abstraction library? The documentation for the PHP setcookiefunction says that the cookie will be available on the next request. Using a command line tool for testing, there is no such thing as a "request". So how can I unit test the correct cookie settings?

I want to test if all the parameters of the setcookie function are set correctly by my abstraction library. Those parameters will be set according to certain conditions and method calls.

The only solution I can think of is to mock the setcookie function with the runkit extension, which I don't want to install. Other ideas?

like image 513
chiborg Avatar asked Dec 21 '10 10:12

chiborg


2 Answers

I found another, very simple solution: A class wrapper around the PHP setcookie function that is so simple, it does not need to be unit tested:

/**
 * Wrapper around setcookie function for better testability
 */ 
class Cookiesetter {
  public function setcookie($name, $value = "",  $expire = 0,  $path = "", 
    $domain = "", $secure = false, $httponly = false) {
    return setcookie($name, $value,  $expire, $path, $domain, $secure, $httponly);
  }
}

The setcookie method can then be mocked. This has the additional benefit that I can implement other methods like expireCookie.

like image 196
chiborg Avatar answered Sep 27 '22 22:09

chiborg


You can set a value directly into the current $_COOKIE array:

<?php
$_COOKIE['test']='hello';
print_r($_COOKIE);
run_tests();

(this works in CLI mode too). Note that $_REQUEST will not be updated by this.

However if you're only trying to manipulate cookies so you can subsequently access the session, why not just access the session directly:

<?php
$_SESSION['auth_user']='root';
run_tests();

But we're talking about unit testing here - not integration testing - which suggests that the code is not very well structured.

like image 42
symcbean Avatar answered Sep 27 '22 22:09

symcbean