如何在Symfony 5.4中的Phpunit testcase中访问EntityManager?
在Symfony 5.4上,我正在对REST API进行测试。 当我尝试访问实体管理器时,我总是会遇到错误,
这是我的测试代码:
<?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()
如何解决此问题?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
WebTestcase
中,您可以这样访问Entity Manager,您也可以在此处查看文档 https://symfony.com/doc/current/testing.html#retrieving-services-in-the-the-test
In
WebTestCase
you can access the entity manager like thisYou can also check the documentation here https://symfony.com/doc/current/testing.html#retrieving-services-in-the-test
EntityManagerInterface上没有方法
get()
。使用方法getRepository(string $ className)
获取存储库:There is no method
get()
on the EntityManagerInterface. Use the methodgetRepository(string $className)
to fetch the repository: