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

Chr*_*sco 11 unit-testing laravel laravel-5

我刚刚添加了tymondesigns/jwt-auth来支持令牌身份验证,因此我的测试用例失败了,因为headers参数上没有令牌.我如何模拟(使用Mockery)组件绕过这个?

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

Rub*_*zzo 10

另一种方法是在测试执行期间通过特定用户验证请求.这是怎么回事:

# 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;
}
Run Code Online (Sandbox Code Playgroud)

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

# 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();
}
Run Code Online (Sandbox Code Playgroud)

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