Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HOW to unit test session variables in PHP?

I run my unit tests through the commandline and it works fine.

But the problem here is when i test a function that contains code that read a session variable, i get a value null..

My guess is you cannot access session variables when you are not in a browser..

How can I do this with PHP? Is this possible?

By the way Im using CodeIgniter 1.7.2 and CIUnit v0.17

Any suggestions or comment would be a great help for me..

Thanks

like image 530
Annie B. Avatar asked Oct 04 '11 04:10

Annie B.


1 Answers

I use a class for the session as Phil suggested. If you call session_start() manually you are binding your code to the PHP session implementation. My call to session_start is protected by my session class with the following:

  if (!isset($_SESSION))
  {
     // If we are run from the command line interface then we do not care
     // about headers sent using the session_start.
     if (PHP_SAPI === 'cli')
     {
        $_SESSION = array();
     }
     elseif (!headers_sent())
     {
        if (!session_start())
        {
           throw new Exception(__METHOD__ . 'session_start failed.');
        }
     }
     else
     {
        throw new Exception(
           __METHOD__ . 'Session started after headers sent.');
     }
  }

Edit:

The above code will go into your session class (and probably be called in some way by its constructor). The command line PHP creates an array instead of calling session_start (which doesn't work on the command line).

When testing code that relies on session variables I mock the session variables in my test:

$_SESSION = array('key1' => 'value you want', 'key2' => 'etc.');

This allows you to test all possible session settings that you will receive on the page.

Testing that the session values are created belongs with the code that creates them in my opinion, so mocking their existence seems ok to me. This way you are testing each unit separately rather than combining them and keeping the session values between the tests.

like image 60
Paul Avatar answered Sep 22 '22 10:09

Paul