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 uninitialized 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:
- PHP Version 5.3.6
- Linux
It happens because at this point:
there is an exception and
session_start();isn’t called anymore.My suggestion would be to change to change your
tearDownto only callsession_destorywhen there is an active session. So in thetearDown“Only clean up if you have to”.