gpt4 book ai didi

c# - 在 Controller 的 MVC **外部**中模拟 HttpContext

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:52 26 4
gpt4 key购买 nike

场景

我们正在开发一个新的 MVC web 项目,并且我们正在尝试遵循本文 http://codebetter.com/iancooper/2008/12/03/the-fat-controller/ 中描述的 Skinny Controller 模式。

作为我们操作的一部分,我们正在从缓存中检索一些导航数据(菜单结构)。

问题

我为了维护瘦 Controller 模式,我们希望在 ViewModel 中进行缓存检查调用,我们已经尝试过并且知道可以使用以下代码。

var cachedCategories = (List<Category>)HttpContext.Current.Cache["Categories"];
if (cachedCategories == null) {
cachedCategories = _service.GetCategories().ToList<Category>();
HttpContext.Current.Cache["Categories"] = cachedCategories;
}

然而,当涉及到单元测试时,我们遇到了问题。由于我们没有直接将 HttpContext 传递到 ViewModel,因此我们不知道如何模拟 HttpContext。

我们正在使用 Moq,虽然我们有一些选项(一个是在实例化时将上下文从 Controller 传递到 View 模型),但这些选项需要纯粹更改代码以使测试工作。

有人有什么建议吗?

最佳答案

模拟 HttpContext 是一项巨大的工作,因为它是您一生中会看到的最大对象之一,所以最好不要模拟它。(http://volaresystems.com/Blog/post/Dont-模拟 HttpContext.aspx)无论如何,您可以使用 MVCcontrib (http://www.codeplex.com/mvcContrib) 中的那个,文件 MvcMockHelps 显示了它是如何完成的。

关于c# - 在 Controller 的 MVC **外部**中模拟 HttpContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6923637/

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