1
我想测试我的应用程序。为了知道我有一个简单的控制器/行动,我从两个不同的学说实体(A和B)打印两个值。如果我从一个实体只有一个值,我的测试工作正常,但对于我目前的情况,它不会工作。PhpUnitTests Doctrine实体
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?
感谢您的回答。但是,你能否给我举一个例子,你认为这会更好吗?那会非常好。 Iam对PhpUnitTests来说是全新的。 – Stillmatic1985
我建议你看看这个[blogpost](http://www.zfdaily.com/2012/07/getting-dependencies-into-zf2-controllers/),了解更多关于通过使用服务工厂。注入仓库而不是entitymanager会使你的控制器使用的仓库变得非常清晰,并且你不会破坏[demeter法则](http://en.wikipedia.org/wiki/Law_of_Demeter)。 –
如果能解决您最初的问题,请您接受答案吗? –