gpt4 book ai didi

cakephp - 如何测试从模型调用 CakeEmail

转载 作者:行者123 更新时间:2023-11-28 20:24:36 25 4
gpt4 key购买 nike

在 CakePHP 2.1 中,我尝试测试 CakeEmail::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();
}

}

最佳答案

问题是您模拟的类与模型上实际使用的类完全不同。在您的模型函数中,您实例化了一个将被模拟的全新电子邮件类。相反,您需要确保模型使用的 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();
}

}

关于cakephp - 如何测试从模型调用 CakeEmail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11523135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com