Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!)

like image 704
stefjnl Avatar asked Jan 21 '14 15:01

stefjnl


People also ask

What is IHttpActionResult?

The IHttpActionResult interface was introduced in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface: Simplifies unit testing your controllers. Moves common logic for creating HTTP responses into separate classes.


1 Answers

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.

like image 166
Karhgath Avatar answered Oct 12 '22 22:10

Karhgath