ASP.NET MVC: Mock controller.Url.Action

前端 未结 5 792
醉话见心
醉话见心 2020-12-14 02:03

Urls for menus in my ASP.NET MVC apps are generated from controller/actions. So, they call

controller.Url.Action(action, controller)

Now, h

5条回答
  •  攒了一身酷
    2020-12-14 02:36

    If you're using Moq (and not MvcContrib's TestControllerBuilder), you can mock out the context, similar to @DarianDimitrov's answer:

    var controller = new OrdersController();
    var context = new Mock().Object;
    
    controller.Url = new UrlHelper(
        new RequestContext(context, new RouteData()),
        new RouteCollection()
    );
    

    This doesn't set the controller.HttpContext property, but it does allow Url.Action to execute (and return an empty string -- no mocking required).

提交回复
热议问题