gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:09:40 28 4
gpt4 key购买 nike

我刚刚添加了 tymondesigns/jwt-auth支持 token 身份验证,因此我的测试用例失败,因为 header 参数上没有 token 。我如何模拟(使用 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();
}

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

关于unit-testing - 如何在 Laravel 5 中模拟 tymondesigns/jwt-auth?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060360/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com