问题 如何在Laravel 5中模拟tymondesigns / jwt-auth?


我刚才补充道 tymondesigns / JWT-AUTH 支持令牌身份验证,因此我的测试用例失败,因为headers参数上没有令牌。我怎么能嘲笑(使用 Mockery)绕过这个的组件?

注意:  $this->be() 不起作用


8378
2018-05-05 18:16


起源

你找到了解决方案吗? - Helder Lucas
我阅读了整个源代码,并模拟了来自jwtauth的每个方法调用。但似乎Laravel 5.1有一个绕过中间件的特性,你可能想看看它 - Christopher Francisco
我对这个解决方案也非常感兴趣。尝试过禁用中间件但无法使其正常工作。你解决了吗? @ChristopherFrancisco - Mattias


答案:


一个 替代 是在测试执行期间通过特定用户验证请求。这是怎么回事:

# tests/TestCase.php

/**
 * Return request headers needed to interact with the API.
 *
 * @return Array array of headers.
 */
protected function headers($user = null)
{
    $headers = ['Accept' => 'application/json'];

    if (!is_null($user)) {
        $token = JWTAuth::fromUser($user);
        JWTAuth::setToken($token);
        $headers['Authorization'] = 'Bearer '.$token;
    }

    return $headers;
}

然后在我的测试中我使用它像这样:

# tests/StuffTest.php

/**
 * Test: GET /api/stuff.
 */
public function testIndex()
{
    $url = '/api/stuff';

    // Test unauthenticated access.
    $this->get($url, $this->headers())
         ->assertResponseStatus(400);

    // Test authenticated access.
    $this->get($url, $this->headers(User::first()))
         ->seeJson()
         ->assertResponseOk();
}

希望这对大家有所帮助。快乐的编码!


9
2017-12-18 09:11