Mocking HttpContextBase with Moq

前端 未结 2 1608
悲哀的现实
悲哀的现实 2020-11-27 16:04

I have a unit test fixture in which I\'m trying to test a ControllerAction on an ASP.NET MVC controller that\'s used for membership functions on a web app. I\'m trying to mo

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 16:50

    I'm using a version of some code Steve Sanderson included in his Pro Asp.NET MVC book... and I'm currently having a moral dilemma whether it's okay to post the code here. How about I compromise with a highly stripped down version? ;)

    So this can easily be reused, create a class similar to the one below that you will pass your controller. This will set up your mocks and set them to your controller's ControllerContext

    public class ContextMocks
    {
        public Moq.Mock HttpContext { get; set; }
        public Moq.Mock Request { get; set; }
        public RouteData RouteData { get; set; }
    
        public ContextMocks(Controller controller)
        {
            //define context objects
            HttpContext = new Moq.Mock();
            HttpContext.Setup(x => x.Request).Returns(Request.Object);
            //you would setup Response, Session, etc similarly with either mocks or fakes
    
            //apply context to controller
            RequestContext rc = new RequestContext(HttpContext.Object, new RouteData());
            controller.ControllerContext = new ControllerContext(rc, controller);
        }
    }
    

    And then in your test method you'd just create an instance of ContextMocks and pass in the controller object you're testing:

    [Test]
    Public void test()
    {
         var mocks = new ContextMocks(controller);
         var req = controller.Request; 
         //do some asserts on Request object
    }
    

    Seems very similar to Craig's examples, but this is with Moq v3. I have to give props to Steve Sanderson for this - I'm using this as a basis for testing all kinds of otherwise traditionally hard-to-test stuff: cookies, session, request method, querystring and more!

提交回复
热议问题