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 setcookie
function 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?
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
.