2016-03-24 19 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类的位置。