gpt4 book ai didi

unit-testing - 使用模拟模型和服务对 Zend Controller 进行单元测试

转载 作者:行者123 更新时间:2023-12-01 22:10:39 25 4
gpt4 key购买 nike

我读过很多 Zend Controller 测试教程,但我找不到解释如何测试使用模型的 Controller 并模拟这些模型的教程。

我有以下 Controller 操作:-

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');
}

此测试有效,但它正在调用真实的模型和服务,这有时意味着它会在测试环境中超时并失败。为了正确地对 Controller 进行单元测试,我需要对 IndexServiceClient 和 IndexModel 进行模拟和期望 - 这是如何完成的?

最佳答案

好吧,由于我在这里看到的回复不多,我会尝试添加我的 2 美分(可能有争议)。下面写的答案是我的 IHMO,非常主观(我认为不是很有用,但我们还是开始吧)

我认为 Controller 不太适合单元测试。你的业务逻辑层、模型等是不可统一的。可以这么说, Controller 与 UI 连接并将系统整合在一起 - 因此对我来说它们更适合集成和 UI 测试 - Selenium 等软件包就是用来做这些的。

在我看来,测试应该足够容易实现,以便测试实现的总工作量足以获得其返回。在我看来(当然,以我有限的知识而言)连接 Controller 的所有依赖项是一项艰巨的任务。

另一种思考方式是 - Controller 中实际发生的情况。同样,IHMO 它应该主要是业务逻辑和 UI 之间的粘合层。如果您将大量业务逻辑放入 Controller 中,则会产生不利影响(例如,它不容易统一测试......)。

当然,这都是理论。希望有人可以提供更好的答案,并实际展示如何轻松连接 Controller 进行单元测试!

关于unit-testing - 使用模拟模型和服务对 Zend Controller 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1707584/

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