我刚刚添加tymondesigns/jwt-auth来支持令牌身份验证,因此我的测试用例失败,因为header参数上没有令牌。我如何模拟(使用Mockery
)组件来绕过它?
注意: $this->be()
无效
答案 0 :(得分:9)
替代是在测试执行期间通过特定用户对请求进行身份验证。这是怎么回事:
# 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();
}
希望这对大家有所帮助。快乐的编码!