doctrine / DoctrineMongoDBBundle

Integrates Doctrine MongoDB ODM with Symfony
http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html
MIT License
382 stars 230 forks source link

How to mock the DocumentManager? #627

Closed tarrsalah closed 4 years ago

tarrsalah commented 4 years ago

I started by aliasing the document manager in services_test.yaml with this entry

test.document_manager: '@Doctrine\ODM\MongoDB\DocumentManager'

Then I replace it during the test

$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);

The test fails because the mock method is never called, and the controller uses the real document manager.

alcaeus commented 4 years ago

How to mock the DocumentManager?

Don't. Only mock what you own. I don't know what you want to do in tests, but mocking the document manager is the wrong way to go at it.

tarrsalah commented 4 years ago

@alcaeus Thanks for the response, I'm trying to mock the DocumentManager in functional tests, (Stackoverflow question with more details https://stackoverflow.com/questions/60805292/how-to-mock-symfony-mongodb-documentmanager-service)

alcaeus commented 4 years ago

To be more specific as to what I was trying to say above: you shouldn't try to mock an object manager. What exactly are you trying to accomplish?

tarrsalah commented 4 years ago

I'm trying to test a controller method that persist a document, I want to test this controller method without hitting the MonogoDB server. So I tried to replace the real document manager with a mock that assert that the persist method is called.

What do you thing of the following approach please?

  1. Create a service (ProductService for example) around the document manager.
  2. Mock this service during the test (I mock what I own).
alcaeus commented 4 years ago

In that case, you'd be wrapping the document manager for the sole purpose of mocking it: it's just as bad. Instead, just write the data to the database, and check that the data has been persisted correctly. Not only does that test your controller, but also your mapping to ensure data is mapped correctly and all necessary data is written.

tarrsalah commented 4 years ago

Thanks for your replies (Learned a lot from them ).

fluchi commented 2 months ago

thank you both for this. very helpful.