Используя Symfony 5, я пытаюсь смоделировать службу MonogDB Document Manager, налагая псевдонимы в конфигурации service_test.yaml
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);
}