问题描述
正如标题所说,我正在用 Symfony 5 构建 API.我有一些控制器需要不同的用户权限,我想测试,所以我决定创建两个具有不同角色的用户进行测试 - ROLE_USER 和 ROLE_ADMIN
.当前代码是这样的(注意,这不是完整的代码,只是一个虚拟示例/起点)
As the title says, I'm building an API with Symfony 5. I have some controllers that require different user permissions that I'd like to test, so I decided to create two users with different roles for testing purpose - ROLE_USER
and ROLE_ADMIN
.The current code is like this (note, it's not full code, just a dummy example/starting point)
ApiTestCase.php
<?php
namespace App\Tests;
use App\Entity\User;
use App\Tests\Http\RequestBuilder;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ApiTestCase extends WebTestCase
{
private static $userData = [
'firstName' => 'Pera',
'lastName' => 'Peric',
'email' => 'test.user@test.com',
'password' => 'test123',
'roles' => [
'ROLE_USER'
]
];
private static $adminUserData = [
'firstName' => 'Admin',
'lastName' => 'Adminovic',
'email' => 'admin.user@test.com',
'password' => 'admin123',
'roles' => [
'ROLE_ADMIN'
]
];
public static function createTestUser()
{
$res = RequestBuilder::create(self::createClient())
->setMethod('POST')
->setUri('/api/v1/security/register')
->setJsonContent(self::$userData)
->getResponse();
$data = $res->getJsonContent();
return $data['data'];
}
public static function createTestAdminUser()
{
$res = RequestBuilder::create(self::createClient())
->setMethod('POST')
->setUri('/api/v1/security/register')
->setJsonContent(self::$adminUserData)
->getResponse();
$data = $res->getJsonContent();
var_dump($data);
return $data['data'];
}
public static function deleteTestUser()
{
self::createClient()->getContainer()
->get('doctrine.orm.entity_manager')
->getRepository(User::class)
->deleteUserByEmail(self::$userData['email']);
}
public static function deleteTestAdminUser()
{
self::createClient()->getContainer()
->get('doctrine.orm.entity_manager')
->getRepository(User::class)
->deleteUserByEmail(self::$adminUserData['email']);
}
}
LocationControllerTest.php
namespace App\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class LocationControllerTest extends ApiTestCase
{
public static $user;
public static $adminUser;
public static function setUpBeforeClass()
{
self::$user = self::createTestUser();
self::$adminUser = self::createTestAdminUser();
}
public function testUsersExist()
{
// this is jut to test out an idea
$this->assertContains('ROLE_USER', self::$user['roles']);
$this->assertContains('ROLE_ADMIN', self::$adminUser['roles']);
}
public static function tearDownAfterClass()
{
self::deleteTestUser();
self::deleteTestAdminUser();
}
}
当我运行测试时(sunit
是别名 php bin/phpunit
):
When I run the test (sunit
is an alias php bin/phpunit
):
➜ skeleton master ✗ (*?) sunit --filter LocationController [10:12AM]
PHPUnit 7.5.17 by Sebastian Bergmann and contributors.
Testing Project Test Suite
E 1 / 1 (100%)
Time: 742 ms, Memory: 24.00 MB
There was 1 error:
1) App\Tests\LocationControllerTest::testUsersExist
LogicException: Booting the kernel before calling Symfony\Bundle\FrameworkBundle\Test\WebTestCase::createClient() is not supported, the kernel should only be booted once. in /Users/shkabo/code/skeleton/vendor/symfony/framework-bundle/Test/WebTestCase.php:44
Stack trace:
#0 /Users/shkabo/code/skeleton/tests/ApiTestCase.php(45): Symfony\Bundle\FrameworkBundle\Test\WebTestCase::createClient()
#1 /Users/shkabo/code/skeleton/tests/LocationControllerTest.php(16): App\Tests\ApiTestCase::createTestAdminUser()
#2 /Users/shkabo/code/skeleton/bin/.phpunit/phpunit-7.5-0/src/Framework/TestSuite.php(703): App\Tests\LocationControllerTest::setUpBeforeClass()
#3 /Users/shkabo/code/skeleton/bin/.phpunit/phpunit-7.5-0/src/Framework/TestSuite.php(746): PHPUnit\Framework\TestSuite->run(Object(PHPUnit\Framework\TestResult))
#4 /Users/shkabo/code/skeleton/bin/.phpunit/phpunit-7.5-0/src/TextUI/TestRunner.php(652): PHPUnit\Framework\TestSuite->run(Object(PHPUnit\Framework\TestResult))
#5 /Users/shkabo/code/skeleton/bin/.phpunit/phpunit-7.5-0/src/TextUI/Command.php(206): PHPUnit\TextUI\TestRunner->doRun(Object(PHPUnit\Framework\TestSuite), Array, true)
#6 /Users/shkabo/code/skeleton/bin/.phpunit/phpunit-7.5-0/src/TextUI/Command.php(162): PHPUnit\TextUI\Command->run(Array, true)
#7 /Users/shkabo/code/skeleton/bin/.phpunit/phpunit-7.5-0/phpunit(17): PHPUnit\TextUI\Command::main()
#8 /Users/shkabo/code/skeleton/vendor/symfony/phpunit-bridge/bin/simple-phpunit.php(291): include('/Users/shkabo/c...')
#9 /Users/shkabo/code/skeleton/bin/phpunit(13): require('/Users/shkabo/c...')
#10 {main}
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
我理解错误,但似乎无法找到它/这种方法的解决方案.而且很有可能我的做法是错误的.
I understand the error, but can't seem to find a solution for it/this approach. Also it's highly possible that I'm doing it the wrong way.
在数据库中,创建了第一个用户,而第二个用户在我尝试创建时抛出此错误.
In the database, first user is created while 2nd one throws this error when I try to create it.
我想要实现的是我有(静态)方法,我可以调用并创建虚拟用户/位置/等.并在该特定控制器的测试中使用它,并在完成该特定控制器的测试后将其从数据库中销毁/删除.
What I want to achieve is that I have (static) methods which I could call and create dummy user/location/etc. and use it in testing of that specific controller, and destroy it/delete it from db upon completing tests of that specific controller.
RequestBuilder
https://github.com/nebkam/fluent-test/blob/master/src/RequestBuilder.php
推荐答案
问题是因为您使用了 2 次 static::createClient()
并且这将再次引导内核.为了避免这种情况,您可以创建一个客户端,然后克隆它并使用方法修改一些参数并将客户端作为参考传递.
The issue is because you are using 2 times static::createClient()
and this will boot again the kernel. To avoid that you can create a client and then clone it and modify some parameters using a method and passing the client as refefence.
在这里你可以找到我昨天在 repo 中写的一个问题以及我找到的解决方案
Here you can find a question I've wrote yesterday in the repo and the solution I found
private static ?KernelBrowser $client = null;
protected static ?KernelBrowser $admin = null;
protected static ?KernelBrowser $user = null;
/**
* @throws \Exception
*/
public function setUp(): void
{
$this->resetDatabase();
if (null === self::$client) {
self::$client = static::createClient();
}
if (null === self::$admin) {
self::$admin = clone self::$client;
$this->createAuthenticatedClient(self::$admin, 'admin@api.com', 'password');
}
if (null === self::$user) {
self::$user = clone self::$client;
$this->createAuthenticatedClient(self::$user, 'user@api.com', 'password');
}
}
protected function createAuthenticatedClient(KernelBrowser &$client, string $username, string $password): void
{
$client->request(
'POST',
'/api/v1/login_check',
[
'_email' => $username,
'_password' => $password,
]
);
$data = \json_decode($client->getResponse()->getContent(), true);
$client->setServerParameter('HTTP_Authorization', \sprintf('Bearer %s', $data['token']));
$client->setServerParameter('CONTENT_TYPE', 'application/json');
}
更多详情请见https://github.com/symfony/symfony/issues/35031
这篇关于Symfony 5 Api 测试 createClient() LogicalException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!