1

在 CakePHP 2.1 中,我正在尝试使用正确的“收件人”电子邮件(在本例中:cat@gmail.com)从我的模型测试用例中调用 CakeEmail::to() 方法。

我希望通过以下测试,但我得到:

Expectation failed for method name is equal to <string:to> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.

这是模型和测试用例中的代码:

<?php

// Model/Job.php

App::uses('AppModel', 'Model');
App::uses('CakeEmail', 'Network/Email');

class Job extends AppModel {

        public function emailCat() {
                $CakeEmail = new CakeEmail();
                $CakeEmail->to('cat@gmail.com');
                $CakeEmail->subject('hello!');
                $CakeEmail->emailFormat('text');
                $CakeEmail->config('default');
                $CakeEmail->send('hi');
        }

}

// Test/Model/JobTest.php

class JobTestCase extends CakeTestCase {

        public function setUp() {
                parent::setUp();
                $this->Job = ClassRegistry::init('Job');
        }      

        public function testEmailCat() {

                // I want to assert CakeEmail::to() is called with correct email
                $CakeEmail = $this->getMock('CakeEmail' , array('to'));
                $CakeEmail->expects($this->once())
                    ->method('to')
                    ->with($this->equalTo('cat@gmail.com'));            

                $result = $this->Job->emailCat();
        }

}
4

1 回答 1

3

问题是您正在模拟一个完全不同的类,而不是模型上实际使用的类。在您的模型函数中,您实例化了一个全新的电子邮件类,该类将被模拟。相反,您需要确保CakeEmail模型使用的对象是模拟对象。

class Job extends AppModel {

        public $CakeEmail = null;  

        public function emailCat() {
                if (!$CakeEmail) {
                        $this->CakeEmail = new CakeEmail();
                }
                $this->CakeEmail = new CakeEmail();
                $this->CakeEmail->to('cat@gmail.com');
                $this->CakeEmail->subject('hello!');
                $this->CakeEmail->emailFormat('text');
                $this->CakeEmail->config('default');
                $this->CakeEmail->send('hi');
        }

}

然后更新您的测试用例以在您的 Job 模型上设置模拟对象。

class JobTestCase extends CakeTestCase {

        public function setUp() {
                parent::setUp();
                $this->Job = ClassRegistry::init('Job');
        }      

        public function testEmailCat() {

                // I want to assert CakeEmail::to() is called with correct email
                $CakeEmail = $this->getMock('CakeEmail' , array('to'));
                $CakeEmail->expects($this->once())
                    ->method('to')
                    ->with($this->equalTo('cat@gmail.com'));  
                // use mock object instead of creating a brand new one          
                $this->Job->CakeEmail = $CakeEmail;
                $result = $this->Job->emailCat();
        }

}
于 2012-07-17T15:01:19.807 回答