Eric Falsken
Eric Falsken

Reputation: 4934

How to unit test MVC/WebAPI with Global Configuration

I want to unit test my controllers, but in my Global.asax.cs file, I have to register things like JSON formatters, custom headers, and AutoMapper mappings. Since the VS Unit test function is testing the controllers by DLL instead of API, the HttpApplication isn't created and a lot of my code fails to test. How can I fix this?

And what's the easiest way to test the JsonFormatter output, since that isn't really part of the controller, but may also be a source of exceptions?

Upvotes: 4

Views: 2313

Answers (2)

S Rosam
S Rosam

Reputation: 385

I had the same issue. For autoMaopper i ran my MapperConfig.Initialize(); in the Setup method for my unit tests (im using NUnit)

I am also calling "WebApiConfig.Register(GlobalConfiguration.Configuration);" in my setup method but the calls to Configuration.Services.GetTraceWriter() in my controllers are coming back with null reference exceptions. So I cant help with that one yet.

Upvotes: 2

nashyura
nashyura

Reputation: 85

To unit test the controllers, I just reference the API DLL in my test suite and exercise the methods directly.

To do more of an integration test, making sure that your routing and mapping is working as expected, I create an HttpClient to the WebApi in my test class, and the look at the response.
The following article gives a good overview for how to call webApi functions from a .NET client: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

Upvotes: 0

Related Questions