在Laravel中的单元/特征测试中存储和检索会话变量

时间:2017-10-09 15:36:08

标签: php laravel session testing phpunit

在Laravel功能测试中,我试图在会话中存储一个变量,以便我可以在其余的测试中使用它,如下所示:

public function testLogin()
{
    $response = $this->json('POST', '/login', $myCredentials);

    $response
        ->assertStatus(200)
        ->assertJson([
            'token' => true
        ]);

    session(['token' => $response['token']]);
}

当我跑#34; phpunit"在命令行中,我收到此错误:

  

PHP致命错误:未捕获的ReflectionException:类会话   不存在于   /vendor/laravel/framework/src/Illuminate/Container/Container.php:752

显然是"会话()"全局帮助程序在测试类中不起作用。我还尝试使用" Illuminate \ Session"直接使用该课程。或只是" \ Session",但两者都返回"未找到"错误。如何在测试类中存储和检索会话变量?

2 个答案:

答案 0 :(得分:0)

在测试中它有点不同。

https://laravel.com/docs/5.2/testing#sessions-and-authentication

以下是一个例子:

public function testApplication()
{
    $this->withSession(['foo' => 'bar'])
         ->visit('/');
}

答案 1 :(得分:0)

有一种您想要的方法。唯一的问题是会话无法使用。

开始测试时,必须生成函数“ master”,该函数将调用其余函数。

    /**
         * Try to login the api client (if you have another middleware use it)
         * @group groupTests
         * @test
         */
        public function masterFunction() {
            //create the body data to try generate the oauth token
            $body = [
                'client_id' => $this->client_id_test,
                'client_secret' => $this->secret,
                'grant_type' => 'client_credentials',
                'scope' => ''
            ];
            //get the response with the data
            $response = $this->json('POST','/oauth/token',$body,['Accept' => 'application/json']);
            //check that return a valid token
            $response->assertStatus(200)->assertJsonStructure(['token_type','expires_in','access_token']);
            //get token data in var
            $token = $response->json("token_type")." ".$response->json("access_token");
            //send string token to the next function
            $this->childrenFunction($token);
        }

构造“子函数”时必须使它们像这样:

/**
     * This function get the token as param
     * @param String $token The token that we want
     * @group groupTests
     */
    private function childrenFunction($token){
        //here can call to $token as a var
        dd($token);
    }

重要的是,“儿童功能”的标题描述中不要包含* @test