【问题标题】:Storing and retrieving session variables in unit/feature tests in Laravel在 Laravel 的单元/功能测试中存储和检索会话变量
【发布时间】:2018-03-20 21:08:32
【问题描述】:

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

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

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

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

当我在命令行中运行“phpunit”时,我得到了这个错误:

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

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

【问题讨论】:

    标签: php laravel session testing phpunit


    【解决方案1】:

    在测试中有点不同。

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

    这是一个例子:

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

    【讨论】:

    • 我要做的是从我的第一个请求中获取一个令牌变量,然后将其存储并在多个类中的多个方法中使用它。我不知道如何使用 withSession() 方法完成此操作,因为我需要的会出现递归问题:“$this->withSession(['token' => session('token')]”。或者我只需要检索每个类的令牌吗?我试图避免不必要的 HTTP 请求。
    • 我想我可以在主测试课上得到一次,然后将其扩展到其他课程。这样我就不需要依赖会话了。
    【解决方案2】:

    有一种方法可以做到这一点。唯一的问题是它不适用于会话。

    当您开始测试时,您必须生成函数“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

    【讨论】:

      猜你喜欢
      • 2016-10-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      相关资源
      最近更新 更多