I started to write Doctrine 2 Mongo ODM unit tests but realized I didn't have a good strategy in my code to do this. I want to run the tests and actually persist the objects but I then want to allow my test data to be easily remove in tearDown. Collection and DB names must be specified from what I've seen in the annotations and can't be overridden so I can't just create a test DB and wipe it out later.
Does anyone have best practices or examples of what they think the best ways to test?
You don't have to persist your objects. The good way is use mock to check if your object was persisted. I'll give you some example. Let say you have a class:
class SomeSerivce
{
private $dm;
public function __construct(DocumentManager $dm)
{
$this->dm = $dm;
}
public function doSomeMagic($someDocument, $someValue)
{
$someDocument->setSomeValue($someValue);
$this->dm->persist($someDocument);
$this->dm->flush();
}
}
Now, you won't check if a document was really persisted because this is tested somewhere id Doctrine code. You can assume that persist
and flush
methods work fine. The thing you want to check is if your code calls these methods correctly.
So, your test could looks like:
(...)
public function testDoSomeMagic()
{
$documment = new Document();
// preapre expected object
$expectedValue = 123;
$expectedDocument = new Document();
$expectedDocument->setValue($expectedValue);
// prepare mock
$dmMock = $this->getMockBuilder('DocumentManager')
->setMethods(array('persist', 'flush'))
->disableOriginalConstructor()
->getMock();
$dmMock->expects($this->once())
->method('persist');
->with($this->equalTo($expectedDocument));
$dmMock->expects($this->once())
->method('flush');
// new we start testing with the mock
$someService = new SomeService($dmMock);
$someService->doSomeMagic($document, $expectedValue);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With