开发者

Unittesting problem with session starting/closing

I am having an problem writing unit tests for an simple session wrapper.

The class itself has some basic functions set, get, exists etc. All these functions have an check assertSessionStart which does the following:

protected static function assertStarted()
{
    if (strlen(session_id()) < 1) {
        throw new Exception("Some text here");
    }
    return;
}

When writing my unit sets, I have the following setUp and tearDown methods. I have these because I want every test that runs to have a fresh session environment.

protected function setUp() {
    session_start();
}
protected function tearDown() {
    session_destroy();
}

Now to the problem, I want an test method which fails when I attempt to use set when I don't have an session started. In order to do this, I will have to destroy the session started in setUp. Like this:

public function testGetWithoutSession() {
        session_destroy();
        $this->setExpectedException('Exception');
        ESL_Session::set('set', 'value');
        session_start();
    }

This however throws an warning 'Trying to destroy uninitializ开发者_Go百科ed session'. When I put an echo session_id() right in front of session_destroy though - it shows me that I have an valid session.

Does anyone have experience unit testing session wrappers?

Additional information:

  1. PHP Version 5.3.6
  2. Linux


It happens because at this point:

    session_destroy();
    $this->setExpectedException('Exception');
    ESL_Session::set('set', 'value'); // HERE <----
    session_start(); // This is not called anymore!

there is an exception and session_start(); isn't called anymore.

My suggestion would be to change to change your tearDown to only call session_destory when there is an active session. So in the tearDown "Only clean up if you have to".


If you have your nice session class wrapper I discourage to use everytime session_id(); for your assert.

Just put a propierty

private $started = false;

and then in your

protected function setUp() {
    session_start();
    $this->started=true;
}

So you can do your assertStarted() based on $started

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜