Laravel 5.0 会话变量的单元测试问题

Laravel 5.0 Unit Testing problems with Session variables

我正在尝试对一些现有代码进行单元测试。我的控制器看起来像

class DefaultController extends Controller
{
    public function index() {
        if (!Session::get('answers', [])) {
            App::abort(403, 'Error.');
        }

        // Do rest of the stuff here
    }
}

我的测试 class 看起来像

class DefaultController extends extends TestCase {
    public function testIndex_withoutSession() {
        // Arrange
        /* Nothing to arrange now */

        // Act
        $this->action('GET', 'DefaultController@index');

        // Assert
        $this->assertResponseStatus(403);
    }

    public function testIndex_withSession() {
        // Arrange
        $this->session(['answers' => array()]);

        // Act
        $this->action('GET', 'ParticipantController@create');

        $this->assertSessionHas('answers');
        // this function is giving true

        // Assert
        $this->assertResponseStatus(200);

        $this->flushSession();
    }
}

我没有会话的测试用例工作正常,但是当我想通过模拟会话变量 'answers' 来检查它时,它仍然给我错误。任何人都可以通过弄清楚我做错了什么或如何正确地做来帮助我吗?没有这个,我无法继续检查代码。 提前致谢。

你有 $this->session(['answers' => array()]); 但是你在这里寻找答案而不是答案 $this->assertSessionHas('answer'); 答案中多出或遗漏 's' 是问题所在。

除了 answer 拼写错误外,answers 数组至少需要一个元素才能通过控制器中的错误检查。测试用例不会断言 200。

要么在测试用例中添加一个值:

$this->session(['answers' => array('something')]);

或更换控制器:

if (!Session::has('answers')) {