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!)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With