Search code examples
c#asp.net-web-apistubmicrosoft-fakes

how to stub HttpControllerContext


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(HttpControllerContext context)
{
    string pub = string.Empty;

    if (context != null)
    {
        pub = context.Request.RequestUri.Segments[2].TrimEnd('/');
    }

    return pub;
}

To Unit-test this i need an HttpControllerContext object. How should i go about it? I was initially trying to stub it with Microsoft Fakes, but HttpControllerContext doesnt seem to have an interface (why??), so thats doesnt seem to be an option. Should i just new up a new HttpControllerContext object and maybe stub its constructor parameters? Or use the Moq framework for this (rather not!)


Solution

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