我刚才补充道 tymondesigns / JWT-AUTH 支持令牌身份验证,因此我的测试用例失败,因为headers参数上没有令牌。我怎么能嘲笑(使用 Mockery
)绕过这个的组件?
注意: $this->be()
不起作用
我刚才补充道 tymondesigns / JWT-AUTH 支持令牌身份验证,因此我的测试用例失败,因为headers参数上没有令牌。我怎么能嘲笑(使用 Mockery
)绕过这个的组件?
注意: $this->be()
不起作用
一个 替代 是在测试执行期间通过特定用户验证请求。这是怎么回事:
# 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();
}
希望这对大家有所帮助。快乐的编码!