0

我想使用模拟测试控制器。

在我的控制器中

public function myAction() {
    $email = new MandrillApi(['template_name'=>'myTemplate']);
    $result = $email
        ->subject('My title')
        ->from('no-reply@test.com')
        ->to('dest@test.com')
        ->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 类?谢谢你

4

1 回答 1

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 类的位置。

于 2016-06-20T14:41:44.790 回答