我读过很多Zend控制器测试教程,但我找不到解释如何测试使用模型和嘲笑这些模型的控制器。单元测试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进行嘲笑和期望 - 这是如何完成的?
在与我的同事们讨论后,得出了同样的结论。使用适当的模拟对控制器进行单元测试需要付出很大的努力,回报很少。尤其是我们的模型层完成了大部分工作,并且具有广泛的测试覆盖范围,而控制器非常薄。 – 2009-11-12 11:09:08