如何在Symfony 5.4的Phpunit测试用例中访问EntityManager?

wooyq4lh  于 2023-02-09  发布在  PHP
关注(0)|答案(2)|浏览(131)

在symfony5.4上,我正在测试一个restapi,当我尝试访问实体管理器时,总是得到错误
我遵循了以下文档:www.example.comhttps://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()

我该如何解决这个问题?

rkkpypqq

rkkpypqq1#

WebTestCase中,您可以像这样访问实体管理器

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

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

nqwrtyyt

nqwrtyyt2#

EntityManagerInterface上没有方法get()。请使用方法getRepository(string $className)提取存储库:

$this->locationRepository = $this->entityManager>getRepository(LocationEntity::class);

相关问题