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

后端 未结 2 1749
遇见更好的自我
遇见更好的自我 2021-02-03 11:47

Update:

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 moc

相关标签:
2条回答
  • 2021-02-03 12:38

    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...

    0 讨论(0)
  • 2021-02-03 12:44

    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.

    0 讨论(0)
提交回复
热议问题