1

使用 Symfony 5,我试图通过在service_test.yaml配置中为其设置别名来模拟 MonogDB 文档管理器服务

services:
    _defaults:
        public: true

    # If you need to access services in a test, create an alias
    # and then fetch that alias from the container. As a convention,
    # aliases are prefixed with test. For example:
    #
    # test.App\Service\MyService: '@App\Service\MyService'
    test.document_manager: '@Doctrine\ODM\MongoDB\DocumentManager'

并用模拟对象替换它

$client = self::createClient();

$mock = $this->getMockBuilder('Doctrine\ODM\MongoDB\DocumentManager')
      ->disableOriginalConstructor()
      ->setMethods(['persist'])
      ->getMock();

$mock->expects($this->once())
    ->method('persist');

$client->getContainer()->set('test.document_manager', $mock);
$client->request(Request::METHOD_POST, '/api/v3/profiles', [], [], [], json_encode(['title' => 'Profile title']));

$response = $client->getResponse();
$this->assertEquals($response->getStatusCode(), Response::HTTP_CREATED);

但是控制器仍然可以访问原始服务

public function create(Request $request, DocumentManager $dm, SerializerInterface $serializer)
{
    $profile = $serializer->deserialize($request->getContent(), Profile::class, 'json');

    $dm->persist($profile);
    $dm->flush();

    return new JsonResponse($serializer->serialize($profile, 'json'), Response::HTTP_CREATED);
}
4

0 回答 0