Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHPUnit to test cookies and sessions, how?

With PHPUnit it's quite easy to test raw PHP code, but what about code that heavily relies on cookies? Sessions could be a good example.

Is there a method that doesn't require me to setup $_COOKIE with data during my test? It feels like a hacky way of doing things.

like image 662
The Pixel Developer Avatar asked Jun 16 '10 01:06

The Pixel Developer


People also ask

What is PHPUnit testing?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.

How do I run a single PHPUnit test?

You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status. The output shows that we ran 1 test, and made 3 assertions in it.


2 Answers

This is a common problem with code, especially lagacy PHP code. The common technique used is to further abstract the COOKIE/SESSION variables in related objects and using inversion of control technique(s) to pull those dependencies into scope.

http://martinfowler.com/articles/injection.html

Now before you execute a test you would instantiate a mock version of a Cookie/Session object and provide default data.

I imagine, the same effect can be achieved with legacy code by simply overriding the super global value before executing the test.

Cheers, Alex

like image 194
user367861 Avatar answered Sep 30 '22 11:09

user367861


I understand this is quite old, but I believe this needs to be updated as technology has improved since the original post. I was able to get sessions working with this solution using php 5.4 with phpunit 3.7:

class UserTest extends \PHPUnit_Framework_TestCase {
    //....
    public function __construct () {
        ob_start();
    }

    protected function setUp() {
       $this->object = new \User();
    }

    public function testUserLogin() {
       $this->object->setUsername('test');
       $this->object->setPassword('testpw');
       // sets the session within:
       $this->assertEquals(true, $this->object->login());
    }
}
like image 35
Etrahkad Avatar answered Sep 30 '22 12:09

Etrahkad