Best practices for HttpContext and testable controllers in ASP.Net MVC

◇◆丶佛笑我妖孽 提交于 2019-12-02 21:04:19

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.

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

For testing I use Rhino.Mocks. To set up the HttpContext in the controller, I simply mocked it. So my system under test (or sut) is something like:

            Controller controllerBase = sut as Controller;

I then mock out the controller context, and set up the context on the controller context to return the mock of the HttpContextBase class (as I mentioned above). My code looks something like:

controllerContext = AMockOf<ControllerContext>();

// Add the test HttpContextBase to the controller context
HttpContextBase httpContextBase = SetUpTestHttpContext();
WhenThe(controllerContext).IsAskedForIts(x =>x.HttpContext).Return(httpContextBase).Repeat.Any();

For other objects I sometimes use fakes as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!