首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Symfony 5 Api测试createClient() LogicalException

Symfony 5 Api测试createClient() LogicalException
EN

Stack Overflow用户
提问于 2019-12-18 09:59:36
回答 3查看 8.9K关注 0票数 7

正如标题所述,我正在使用Symfony 5构建一个API。我有一些控制器需要不同的用户权限来测试,所以我决定为测试目的创建两个角色不同的用户-- ROLE_USERROLE_ADMIN。当前的代码如下(注意,它不是完整的代码,只是一个虚拟的示例/起点)

ApiTestCase.php

代码语言:javascript
复制
<?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

代码语言:javascript
复制
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):

代码语言:javascript
复制
➜  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.

我理解错误,但似乎无法找到解决方案/这种方法。而且很有可能我做错了。

在数据库中,第一个用户被创建,而第二个用户在我试图创建它时抛出这个错误。

我想实现的是,我有(静态)方法,我可以调用和创建虚拟用户/位置/等等,并使用它测试该特定控制器,并在完成该特定控制器的测试后将其销毁/从db中删除。

RequestBuilder

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-12-19 09:25:53

问题在于您正在使用2次static::createClient(),这将再次引导内核。为了避免这种情况,您可以创建客户端,然后使用方法复制并修改某些参数,并将客户端作为refefence传递。

在这里你可以找到我昨天在回购和我找到的解决方案中写的一个问题

代码语言:javascript
复制
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的更多细节

票数 5
EN

Stack Overflow用户

发布于 2020-09-15 18:02:04

您可以根据官方推荐在创建客户端之前调用self::ensureKernelShutdown()

代码语言:javascript
复制
self::ensureKernelShutdown();
$sally = static::createClient();

我不确定这是否解决了这个问题,但我也遇到了一个类似的问题,谷歌让我来到了这里。

https://github.com/symfony/symfony-docs/issues/12961

票数 15
EN

Stack Overflow用户

发布于 2020-08-24 13:04:50

我也有同样的问题,并通过在Client中初始化setUp()来解决。

代码语言:javascript
复制
protected function setUp(): void
{
    $this->client = $this->makeClient();
    $this->client->followRedirects();
    ...
}

在测试中,我使用$this->client->loginUser()登录以身份验证防火墙类型作为第二个参数的用户。

代码语言:javascript
复制
public function testWhateverYouNeed(): void
{
    ... // Get the user from fixtures
    $this->client->loginUser($user, 'admin');
}

防火墙是在config/packages/security.yaml中定义的

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59389497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档