会话开始/结束时的单元测试问题

Wes*_*orp 4 php phpunit unit-testing

我在为简单的会话包装器编写单元测试时遇到问题.

这个类本身有一些基本的功能set,get,exists等.所有这些功能有一个检查assertSessionStart其执行以下操作:

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

在编写我的单位集时,我有以下setUptearDown方法.我有这些因为我希望每个运行的测试都有一个新的会话环境.

protected function setUp() {
    session_start();
}
protected function tearDown() {
    session_destroy();
}
Run Code Online (Sandbox Code Playgroud)

现在问题,我想要一个测试方法,set当我没有开始会话时尝试使用它.为了做到这一点,我将不得不破坏开始的会话setUp.像这样:

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

然而,这会发出警告"试图破坏未初始化的会话".当我把一个echo session_id()权利放在前面时session_destroy- 它告诉我我有一个有效的会话.

有没有人有经验单元测试会话包装?

其他信息:

  1. PHP版本5.3.6
  2. Linux的

edo*_*ian 5

这是因为在这一点上:

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

有一个例外,session_start();不再被调用.

我的建议是更改为在有活动会话时将您更改tearDown为仅调用session_destory.所以在tearDown "只有你必须清理"中.

  • 或者你可以捕获异常而不是使用`setExpectedException()`.在调用`set()`之后在try块中添加`self :: fail()`. (2认同)