Showing posts with label testing. Show all posts
Showing posts with label testing. Show all posts

Tuesday, November 25, 2014

Mocking controller context and route data for Web API controller (OAuth attribute)

ASP.NET Web API 2 is a great technology for creating RESTful web services.

However, there can be a challenge for unit testing if you need to mock the OAuth "Authorize" attribute on a controller's method.

This is where Moq comes in.  It's available here - https://github.com/Moq/moq4 .

So, say if you have a controller method that uses the OAuth "Authorization" attribute and it needs unit test coverage then you can use Moq to setup your test.

Example psuedocode for controller method:

[OAuthAuthorization]
public CustomData GetCoolData()
{
    // get data from route here
    // more business logic
    return CustomData object;
}

--------------

Example helper for setting up controller context and route data:
public HttpControllerContext SetupControllerContext(ApiController controller)
{
    controller.ControllerContext = // new one up here or call another helper to populate object
    controller.ControllerContext.Request = new HttpRequestMessage();
    controller.ControllerContext.Request.Headers.Add("Authorization", "Bearer fakeToken");
    controller.ControllerContext.RouteData = new HttpRouteData(new HttpRoute());
    // Add any key value pairs to route data here
    controller.ControllerContext.RouteData.Values.Add("key", valueObject);

    return controller.ControllerContext;
}


Example test code snippet:

// Arrange
_controller.ControllerContext = SetupControllerContext(_controller);
// Setup mock here to mock the data provider and return what you'd like or throw if negative test

// Act
var result = _controller.GetCoolData();

// Assert
Assert.IsNotNull(result);
// do any further validation

That's pretty much it.  There wasn't much online about how to do this so I wanted to share.  Cheers.