【发布时间】:2018-10-02 21:07:48
【问题描述】:
我是单元/集成测试的新手,我想对我的控制器进行集成测试,看起来像这样简化:
// ItemsController.php
public function edit() {
// some edited item
$itemEntity
// some keywords
$keywordEntities = [keyword1, keyword2, ...]
// save item entity
if (!$this->Items->save($itemEntity)) {
// do some error handling
}
// add/replace item's keywords
if (!$this->Items->Keywords->replaceLinks($itemEntity, $keywordEntities)) {
// do some error handling
}
}
我有模型 Items 和 Keywords 其中 Items 属于ToMany 关键字。我想测试控制器的错误处理部分。所以我必须模拟 save() 和 replaceLinks() 方法,它们将返回 false。
我的集成测试如下所示:
// ItemsControllerTest.php
public function testEdit() {
// mock save method
$model = $this->getMockForModel('Items', ['save']);
$model->expects($this->any())->method('save')->will($this->returnValue(false));
// call the edit method of the controller and do some assertions...
}
这适用于 save() 方法。但它不适用于 replaceLinks() 方法。显然是因为它不是模型的一部分。
我也试过这样的:
$method = $this->getMockBuilder(BelongsToMany::class)
->setConstructorArgs([
'Keywords', [
'foreignKey' => 'item_id',
'targetForeignKey' => 'keyword_id',
'joinTable' => 'items_keywords'
]
])
->setMethods(['replaceLinks'])
->getMock();
$method->expects($this->any())->method('replaceLinks')->will($this->returnValue(false));
但这也行不通。模拟 replaceLinks() 方法的任何提示?
【问题讨论】:
标签: testing cakephp cakephp-3.0