在CakePHP 2.1中我试图测试CakeEmail :: to()方法是从我的模型测试用例中使用正确的“to”电子邮件调用的(在这个例子中:cat@gmail.com)。
我想通过以下测试,但我得到了:
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();
}
}
答案 0 :(得分: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');
}
}
然后更新测试用例以在作业模型上设置模拟对象。
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();
}
}