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 :
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.