【问题标题】:How to access the EntityManager in a Phpunit Testcase in Symfony 5.4?如何在 Symfony 5.4 的 Phpunit 测试用例中访问 EntityManager?
【发布时间】:2023-02-05 21:55:44
【问题描述】:

在 symfony 5.4 上,我正在测试一个 rest api。 当我尝试访问实体管理器时总是出错

我遵循了这个文档: https://symfony.com/doc/current/testing/database.html#functional-testing-of-a-doctrine-repository

这是我的测试代码:

<?php
namespace App\Tests;

use App\Repository\LocationRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Response;

class DataTest extends WebTestCase     // WebTestCase  (not KernelTestCase)
{
    private EntityManagerInterface $entityManager;
    private LocationRepository $locationRepository;

    protected function setUp(): void
    {
        $kernel = self::bootKernel();
        $this->entityManager = $kernel->getContainer()
            ->get('doctrine')
            ->getManager();
        $this->locationRepository = $this->entityManager->get(LocationRepository::class);
    }

    protected function tearDown(): void
    {
        parent::tearDown();

        // doing this is recommended to avoid memory leaks
        $this->entityManager->close();
        $this->entityManager = null;
    }

    public function test401(): void
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/api/locations');
        $response = $client->getResponse();
        $this->assertResponseStatusCodeSame(401);
    }
...

我收到此错误:

Testing App\Tests\DataTest
EEEE                                                                4 / 4 (100%)

There were 4 errors:

1) App\Tests\DataTest::test401
Error: Call to undefined method ContainerDyLAo2g\EntityManager_9a5be93::get()

我该如何解决这个问题?

【问题讨论】:

    标签: symfony phpunit


    【解决方案1】:

    WebTestCase你可以像这样访问实体管理器

    $this->entityManager = static::getContainer()->get(EntityManagerInterface::class)
    

    您也可以在这里查看文档https://symfony.com/doc/current/testing.html#retrieving-services-in-the-test

    【讨论】:

    • 不必是WebTestCase,可以很容易地成为KernelTestCase。前者更多用于发送 HTTP 请求。
    猜你喜欢
    • 2017-11-10
    • 2019-11-22
    • 1970-01-01
    • 2018-09-18
    • 2017-07-28
    • 1970-01-01
    • 2021-09-10
    • 2022-01-07
    • 2020-08-09
    相关资源
    最近更新 更多