ASP.Net MVC中HttpContext和可测试控制器的最佳实践 [英] Best practices for HttpContext and testable controllers in ASP.Net MVC

查看:38
本文介绍了ASP.Net MVC中HttpContext和可测试控制器的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:

基于我收到的几个答案,我只是想表明我很清楚如何使用模拟框架来模拟HttpContext. 我更感兴趣的是,与在HttpContext周围使用包装器类相比,嘲笑HttpContext的优缺点是什么.

Based on a couple of the answers I have received, I just want to make clear that I am well aware how to go about mocking HttpContext using a mocking framework. I am more interested knowing what the pros and cons of mocking HttpContext are when compared to using wrapper classes around HttpContext.

在ASP.Net MVC中构建可测试的控制器时,我正在寻找有关如何处理HttpContext的意见.阅读完该书之后,似乎有两种思路:要么基于HttpContextBase构建并使用模拟框架生成单元测试所需的存根/模拟项,要么围绕打算使用的HttpContext区域构建不可知的包装类.

I'm looking for opinions on how to deal with HttpContext when building testable controllers in ASP.Net MVC. After reading up on it there seems to be two schools of thought - either build off of HttpContextBase and use a mocking framework to generate the needed stubs/mocks for your unit testing or build agnostic wrapper classes around the areas of HttpContext which you intend to use.

现在,我倾向于构建HttpContextBase.似乎既加快了开发过程,又使维护更加容易,因为您不必花时间开发和维护其他包装器类.我可以看到包装器类可能会受益,因为它们将基础实现抽象化,并使控制器的上下文与请求分离开来,但是我不确定这是否值得设置和维护额外的开销.

Right now I am leaning towards building off of HttpContextBase. It seems like it is both the faster development process and easier to maintain as you don't have to spend time developing and maintaining additional wrapper classes. I can see how the wrapper classes might be beneficial as they abstract away the underlying implementation and keep the controller's context separate from the request - but I'm not sure if this is worth the extra overhead to setup and maintain.

您觉得这两种方法之间的优缺点是什么,何时选择一种?是否有某些类型的开发更适合其中一种解决方案?

What do you feel are the pros and cons between these two approaches and when would you choose one over the other? Are there certain types of development that lend itself to one of the solutions more so than the other?

由于这似乎是一个常见问题,大多数正在进行单元测试和使用ASP.Net MVC的团队都必须处理,您将如何处理这个问题?如果您已经解决了这个问题,那么您的解决方案是如何工作的,现在又有什么不同呢?

As this seems like a common issue most teams who are unit testing and using ASP.Net MVC have to deal with, how would you or have you gone about handling this issue? If you have addressed this issue, how did your solution work and what would you do differently now?

推荐答案

我倾向于HttpContextBase.主要是因为我认为它是出于以下原因而发明的:可测试性.以及为什么在已有可接受的解决方案的情况下重新发明轮子.

I'm leaning towards HttpContextBase. Mainly because I think it was invented for just this reason: testability. And why reinvent the wheel when there's an acceptable solution already out there.

如果您对HttpContext的包装器类进行了大量工作,最终将得到与HttpContextBase非常相似的东西...

If you put a lot of effort into your wrapper classes around HttpContext, you'd end up with something very similar to HttpContextBase...

这篇关于ASP.Net MVC中HttpContext和可测试控制器的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆