我如何模拟“Dingo\Api\Auth\Provider\JWT”,以便在对端点进行单元测试时绕过身份验证overhwad?
我在我的 api 中使用 dingo/api
,我想对端点进行单元测试:
class MyApiTest extends TestCase
{
public function testEndpoint()
{
$dispatcher = app('Dingo\Api\Dispatcher');
$fake_token = 'cndksjonsdcnsod';
$dispatcher->header('Authorization', 'Bearer: '.$fake_token);
$dispatcher->version($version)->get('/my-endpoint');
}
}
在我的 app.php
中,我有以下配置:
'auth' => [
'jwt' => Dingo\Api\Auth\Provider\JWT::class,
],
有没有办法模拟/伪造/将默认值设置为 jwt 身份验证的 Dingo\Api\Auth\Provider\JWT
提供商?
I am using dingo/api
in my api and I want to unit test the endpoint:
class MyApiTest extends TestCase
{
public function testEndpoint()
{
$dispatcher = app('Dingo\Api\Dispatcher');
$fake_token = 'cndksjonsdcnsod';
$dispatcher->header('Authorization', 'Bearer: '.$fake_token);
$dispatcher->version($version)->get('/my-endpoint');
}
}
In my app.php
I have the following configuration:
'auth' => [
'jwt' => Dingo\Api\Auth\Provider\JWT::class,
],
Is there a way to mock/fake/set default values to the Dingo\Api\Auth\Provider\JWT
provider of jwt authentication?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对我有用的一种方法是通过绕过 Dingo 和路由本身使用的任何中间件来测试控制器本身并模拟 JWT 身份验证服务。
示例:
假设我们有以下控制器:
您可以编写一个简单的测试:
在我们的例子中,我们不关心使用什么路由以及如何设置它。因此,在这个例子中没有提及任何路由和任何有关 Dingo 的事情,我们只是忘记它。
缺点和优点
虽然它不是灵丹妙药,但它是一种可以针对实际代码提供可靠结果的方法。请记住,尽管您绕过了许多您可能也想测试的中间件,例如。认证的。
另一方面,您可以测试控制器内部的逻辑,如果逻辑相当小,无法为其创建单独的类/方法,例如。从数据库中选择数据。
An approach that worked for me, is via testing the controller itself and mock JWT authentication service by bypassing the Dingo and any middleware used by routing itself.
Example:
Let us suppose we have the following controller:
You can write a simple test:
In our case we do not care about what routing is used and how it is set up. Therefore, are no mentioning any routing and anything regarding Dingo in this example, we just forget it.
Cons and pros
Though it is not a silver bullet, it is an approach that will give a reliable result focusing on the actual code. Keep in mind though that you bypass many middlewares that may you also want to test as well eg. Authentication ones.
On the other hand you are able to test the logic inside the controller, in cases where the logic is rather small to create a seperate class/method for it eg. selecting data from DB.