2016-03-11 24 views
0

我目前正在致力於ZF2/Doctrine項目,我正試圖讓我的PHPUnit套件正常運行。第一次嘗試編寫一個ZF2項目的單元測試,一個Doctrine項目以及第一次與Mockery合作。到目前爲止這麼好,但是我遇到了Doctrine EntityManager的問題;我可以結合shouldReceive和shouldNotReceive在Mockery中使用Doctrine Entity Manager在ZF2中進行控制器測試嗎?

我剛剛嘲笑我的Doctrine\Orm\EntityManager,我想要一個getRepository與某個參數調用返回一個模擬的存儲庫,但我希望對其他存儲庫的調用保持不變。我認爲使用shouldReceiveshouldNotReceive彼此並行將工作,但不知何故,我不斷收到錯誤;

class ProductControllerTest extends AbstractHttpControllerTestCase 
{ 
    public function testViewAction() 
    { 
     $serviceLocator = $this->getApplicationServiceLocator(); 
     $entityManager = \Mockery::mock($serviceLocator->get('Doctrine\ORM\EntityManager')); 

     $entityManager 
      ->shouldReceive('getRepository') 
      ->with('App\Entity\Product') 
      ->andReturn(\Mockery::mock('App\Repository\Product')); 

     $entityManager 
      ->shouldNotReceive('getRepository') 
      ->with(\Mockery::not('App\Entity\Product')); 

     $serviceLocator 
      ->setAllowOverride(true) 
      ->setService('Doctrine\ORM\EntityManager', $entityManager); 

     $this->dispatch('/products/first-product'); 

     $this->assertResponseStatusCode(200); 
    } 
} 

我想要這個特定的事情的原因是因爲我只是想爲這段代碼寫一個測試。一些底層代碼並不完美,所以請幫助我專注於這一部分,但我希望能夠在不破壞應用程序的情況下重構底層代碼片段。必須開始某處使我的應用程序完全可測試;)

但是有什麼我的邏輯中有缺陷或缺少什麼?非常感謝!

回答

1

你可以嘗試這樣的事情。這個想法是首先使用byDefault()設置一個默認期望值,然後定義你的特定期望值,這比默認值更受歡迎。

$entityManager 
    ->shouldReceive('getRepository') 
    ->with(\Mockery::any()) 
    ->andReturn(\Mockery::mock('Doctrine\ORM\EntityRepository')) 
    ->byDefault(); 

$entityManager 
    ->shouldReceive('getRepository') 
    ->with('App\Entity\Product') 
    ->andReturn(\Mockery::mock('App\Repository\Product')); 
相關問題