在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()
我该如何解决这个问题?
2条答案
按热度按时间rkkpypqq1#
在
WebTestCase
中,您可以像这样访问实体管理器您也可以在www.example.com查看文档https://symfony.com/doc/current/testing.html#retrieving-services-in-the-test
nqwrtyyt2#
EntityManagerInterface上没有方法
get()
。请使用方法getRepository(string $className)
提取存储库: