2013-12-17 59 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

如果能解決您最初的問題,請您接受答案嗎? –