收录日期:2019/08/19 20:50:19 时间:2010-06-16 01:21:36 标签:php,unit-testing,session,cookies,phpunit

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.

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

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());
    }
}