how to stub HttpControllerContext

后端 未结 1 927
执笔经年
执笔经年 2020-12-29 11:04

I am trying to unit-test a piece of code that gets called from a WebAPI (OData) controller and takes in an HttpControllerContext:

public string MethodToTest(         


        
相关标签:
1条回答
  • 2020-12-29 11:13

    You can simply instantiate an HttpControllerContext and assign context objects to it, in addition to route information (you could mock all of these):

    var controller = new TestController();
    var config = new HttpConfiguration();
    var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/test");
    var route = config.Routes.MapHttpRoute("default", "api/{controller}/{id}");
    var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "test" } });
    
    controller.ControllerContext = new HttpControllerContext(config, routeData, request);
    controller.Request = request;
    controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
    
    // Call your method to test
    MethodToTest(controller);
    

    HttpControllerContext is simply a container so it does not have to be mocked itself.

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