【发布时间】:2026-01-26 09:50:02
【问题描述】:
我已经阅读了很多 Zend 控制器测试教程,但我找不到一个解释如何测试使用模型的控制器并模拟这些模型的教程。
我有以下控制器动作:-
function indexAction(){
// Get the cache used by the application
$cache = $this->getCache();
// Get the index service client and model
$indexServiceClient = new IndexServiceClient($this->getConfig());
$indexModel = $this->_helper->ModelLoader->load('admin_indexmodel', $cache);
$indexModel->setIndexServiceClient($indexServiceClient);
// Load all the indexes
$indexes = $indexModel->loadIndexes();
$this->view->assign('indexes', $indexes);
}
目前我有一个非常基本的测试用例:-
public function testIndexActionRoute() {
$this->dispatch( '/admin/index' );
$this->assertModule('admin', 'Incorrect module used');
$this->assertController('index', 'Incorrect controller used');
$this->assertAction('index', 'Incorrect action used');
}
此测试有效,但它正在调用真实的模型和服务,这有时意味着它会超时并在测试环境中失败。为了正确地对控制器进行单元测试,我需要对 IndexServiceClient 和 IndexModel 进行模拟和期望 - 这是如何完成的?
【问题讨论】:
标签: unit-testing zend-framework