2013-12-17 142 views
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?

回答

1

您可以使用with()方法来定义您想要设置您的模拟的具体方法参数。即:

$entityManager 
    ->expects($this->once()) 
    ->method('getRepository') 
    ->with($this->equalTo('MyNamespace\Repository\RepositoryA')) 
    ->will($this->returnValue($aRepository)); 

而对于回购b

类似顺便说一句这将是清洁通过控制器工厂以注入的EntityManager到控制器中。或者更好的是,注入这两个存储库作为依赖。它会使事情变得更清洁,更容易测试。

+0

感谢您的回答。但是,你能否给我举一个例子,你认为这会更好吗?那会非常好。 Iam对PhpUnitTests来说是全新的。 – Stillmatic1985

+0

我建议你看看这个[blogpost](http://www.zfdaily.com/2012/07/getting-dependencies-into-zf2-controllers/),了解更多关于通过使用服务工厂。注入仓库而不是entitymanager会使你的控制器使用的仓库变得非常清晰,并且你不会破坏[demeter法则](http://en.wikipedia.org/wiki/Law_of_Demeter)。 –

+0

如果能解决您最初的问题,请您接受答案吗? –