开发者

How to unit test session wrapper class?

I have simple session wrapper class with getters and setters to deal with $_SESSION in OO style. session_start() is called in __constructor(). What is the best practice to unit test this class?

  1. As w开发者_开发技巧e're running unit tests from CLI - we can't truly create session, but we can define $_SESSION variables in test setup or any other place in test. What is the best practice to emulate web session? Maybe I should create some kind of testing environment with all server variables being set?

  2. PHPUnit_Framework_Error_Warning : E_WARNING: session_start(): Cannot send session cookie - headers already sent by (output started at C:\Users\Kir\AppData\Local\Temp\phpunit_go_Kir.php:770) - how to avoid this? How to prevent PHP Unit Test output Testing started at 12:59 ...

PS: Sorry for questions, but I've started to write unit tests only yesterday and I have no enough experience at the moment.

Thank you.


Calling session_start in your code binds you to PHP's session_start implementation. Actually, the idea of a session makes little sense in CLI. You can guard your session_start calls with the following code in your class:

  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.');
     }
  }

I have kept my session class to be just about this code (plus a simple id function for session_id). Testing on the CLI can continue as the session_start call has been guarded against. Actually testing the code I pasted is hard though. You can test it by observation under a browser outside of your normal CLI testing. At least all of your other CLI testing will now be unaffected by session_start calls.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜