2016-03-24 212 views
0

我想用模擬來測試一個控制器。Cakephp 3使用模擬來測試控制器

在我的控制器

public function myAction() { 
    $email = new MandrillApi(['template_name'=>'myTemplate']); 
    $result = $email 
     ->subject('My title') 
     ->from('[email protected]') 
     ->to('[email protected]') 
     ->send(); 

    if (isset($result[0]['status']) && $result[0]['status'] === 'sent') 
     return $this->redirect(['action' => 'confirmForgotPassword']); 

    $this->Flash->error(__("Error")); 
} 

在測試

public function testMyAction() { 
     $this->get("users/my-action"); 
     $this->assertRedirect(['controller' => 'Users', 'action' => 'confirmForgotPassword']); 
    } 

如何嘲笑類MandrillApi?謝謝

+0

我首先會評估你是否真的需要嘲笑課程。我猜你不想將數據發送到測試中的實時API?鑑於你沒有通過任何憑據,我會假設該類讀取一些全局配置值?也許可以配置它,以便將數據發送到虛擬端點? – ndm

+0

是的,可能需要通過此API的測試密鑰,但是我想知道是否可以在控制器中模擬一個類 – Ozee

回答

2

在你的控制器測試:

public function controllerSpy($event){ 
    parent::controllerSpy($event); 
    if (isset($this->_controller)) { 
     $MandrillApi = $this->getMock('App\Pathtotheclass\MandrillApi', array('subject', 'from', 'to', 'send')); 
     $this->_controller->MandrillApi = $MandrillApi; 
     $result = [ 
      0 => [ 
       'status' => 'sent' 
      ] 
     ]; 
     $this->_controller->MandrillApi 
      ->method('send') 
      ->will($this->returnValue($result)); 
    } 
} 

的controllerSpy方法將插入嘲笑對象一旦控制器是否設置正確。您不必調用controllerSpy方法,在您測試中進行$this->get(...調用後,它會在某個時刻自動執行。

很明顯,您必須更改App\Pathtotheclass-模擬代的一部分以適應您的MandrillApi類的位置。

相關問題