【发布时间】:2018-07-21 20:26:49
【问题描述】:
我正在尝试使用 PHPUnit 测试使用 Symfony 4 制作的控制器。 我正在使用https://github.com/lexik/LexikJWTAuthenticationBundle 来管理 JWT。
如果给出有效的 JWT,则此控制器应返回 200,否则返回 401/403。
401 响应的第一部分很简单:我只是不发送任何令牌
<?php
namespace App\Tests\Controller;
Class GraphQLControllerTest extends \Symfony\Bundle\FrameworkBundle\Test\WebTestCase {
function test_token(){
$client = static::createClient();
$client->request('GET', '/graphql');
// Check 401 response
$response = $client->getResponse();
$this->assertSame(401, $response->getStatusCode());
$this->assertSame('"Not authenticated"', $response->getContent());
}
}
接下来的部分比较棘手:如何在我的 test_token 方法中获取我的 JWT 编码器服务,以便生成一些令牌来测试 200 和 403 响应?
如果我在控制器中,我可以使用 Symfony 自动装配或创建 lexik_jwt_authentication.encoder 的公共别名以像这样使用:
$this->container->get('lexik_jwt_authentication.encoder')
像下面这样在我的测试中手动加载服务似乎效率低下,因为构造函数的一些参数是一些对象,而它们自己的构造函数的一些参数是对象,并且......
new Lexik\Bundle\JWTAuthenticationBundle\Encoder\DefaultEncoder([some objects here])
这就是自动装配的好处:您只需准备好要使用的服务。
=> 在我的测试中获得这项服务的最佳方式是什么?
谢谢!
【问题讨论】:
-
在一个服务中包含所有聪明的逻辑不是更好吗,这样比控制器更容易测试?
-
@CalamityJane 我不确定您的解决方案:该服务也将具有需要连接的依赖项
标签: dependency-injection functional-testing symfony4