ShaunP
ShaunP

Reputation: 473

Unit Testing WEBAPI Controllers

I have a webapi controller that I am trying to unit test. However I am struggling to resolve the different types of ControllerContext. Most of the code examples I see are to do with testing MVC controllers and not Web API controllers.

The controller is defined as:

public class OrdersController : ApiController
{

I have this code which works when I run the application

uri = Url.Route("DefaultRoute", new { httproute = true, Id = order.Id});

However when I try to run it as a unit test, it fails. I have debugged it and find that Url is null when running unit tests, whereas if I run the system normally Url is an object of type System.Web.Http.Routing.UrlHelper.

Any idea how I can get Url.Route() to work when running unit tests?

Upvotes: 0

Views: 2430

Answers (1)

cecilphillip
cecilphillip

Reputation: 11586

For units tests in Web API 2, the easier option is for you to provide a Mock version the UrlHelper to your controller instance. This examples uses Moq

        var mockUrlHelper = new Mock<UrlHelper>();    
        ordersCtrl.Url = mockUrlHelper.Object;

If you're using a later version of web api, you'd have populate the controller in your test with RouteData. This sample is taken from the asp.net website :

 controller.Configuration = new HttpConfiguration();
 controller.Configuration.Routes.MapHttpRoute(
    name: "DefaultApi", 
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional });

 controller.RequestContext.RouteData = new HttpRouteData(
    route: new HttpRoute(),
    values: new HttpRouteValueDictionary { { "controller", "products" } });

Upvotes: 1

Related Questions