单元测试Doctrine ODM

时间:2012-03-16 07:14:12

标签: testing doctrine phpunit

我开始编写Doctrine 2 Mongo ODM单元测试,但发现我的代码中没有一个好的策略来执行此操作。我想运行测试并实际持久保存对象,但我想让我的测试数据在tearDown中轻松删除。必须从我在注释中看到的内容中指定集合和数据库名称,并且不能覆盖它,因此我不能仅创建测试数据库并稍后将其擦除。

有没有人有他们认为最佳测试方法的最佳实践或示例?

1 个答案:

答案 0 :(得分:10)

您不必坚持您的对象。好的方法是使用mock来检查你的对象是否被持久化。我会给你一些例子。假设你有一个班级:

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();
     }
 }

现在,您不会检查文档是否真的存在,因为这是在ID Doctrine代码的某处测试的。您可以假设persistflush方法正常工作。您要检查的是您的代码是否正确调用这些方法。

所以,你的测试看起来像:

 (...)
 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);
}
相关问题