Doctrine orm 实体主义
我想测试我的应用程序。例如,我有一个简单的控制器/操作,其中我打印来自两个不同条令实体(a和B)的两个值。如果我从一个实体中只有一个值,我的测试可以正常工作,但对于我目前的情况,它将无法工作Doctrine orm 实体主义,doctrine-orm,zend-framework2,phpunit,Doctrine Orm,Zend Framework2,Phpunit,我想测试我的应用程序。例如,我有一个简单的控制器/操作,其中我打印来自两个不同条令实体(a和B)的两个值。如果我从一个实体中只有一个值,我的测试可以正常工作,但对于我目前的情况,它将无法工作 public function testIndexActionCanBeAccessed() { $a = $this->getMock('\Application\Entity\A'); $a->expects($this->once())->method('get
public function testIndexActionCanBeAccessed()
{
$a = $this->getMock('\Application\Entity\A');
$a->expects($this->once())->method('getName')->will($this->returnValue('A'));
$b= $this->getMock('\Application\Entity\B');
$b->expects($this->once())->method('get')->will($this->returnValue('B'));
$aRepository = $this->getMockBuilder('\Doctrine\ORM\EntityRepository')->disableOriginalConstructor()->getMock();
$aRepository->expects($this->once())->method('find')->will($this->returnValue($a));
$bRepository = $this->getMockBuilder('\Doctrine\ORM\EntityRepository')->disableOriginalConstructor()->getMock();
$bRepository->expects($this->once())->method('find')->will($this->returnValue($b));
$entityManager = $this->getMockBuilder('\Doctrine\Common\Persistence\ObjectManager')->disableOriginalConstructor()->getMock();
$entityManager->expects($this->once())->method('getRepository')->will($this->returnValue($aRepository));
$entityManager->expects($this->any())->method('getRepository')->will($this->returnValue($bRepository));
$this->getApplicationServiceLocator()->setAllowOverride(true);
$this->getApplicationServiceLocator()->setService('\Doctrine\ORM\EntityManager', $entityManager);
$this->dispatch('/myroute/');
$this->assertResponseStatusCode(200);
}
如何告诉entitymanager可能有多个getRepository?您可以使用with()
方法定义要为其设置模拟的特定方法参数。即:
$entityManager
->expects($this->once())
->method('getRepository')
->with($this->equalTo('MyNamespace\Repository\RepositoryA'))
->will($this->returnValue($aRepository));
回购b的情况也类似
顺便说一句,通过控制器工厂将entityManager注入控制器会更干净。或者更好的是,将这两个存储库作为依赖项注入。这将使事情变得更干净、更容易测试。谢谢您的回答。但你能给我举个例子,说明你认为怎样做会更好吗?那太好了。我对phpunittes完全是新手。我建议您看看这篇文章,了解更多关于使用服务工厂在控制器中获取依赖关系的信息。注入存储库而不是entitymanager将非常清楚您的控制器使用哪些存储库,并且您不会违反规则。如果它解决了您最初的问题,您能接受答案吗?