I'm trying to write some unit tests to ensure that requests made to my Web API are routed to the expected API controller action with the expected arguments.
I've tried to create a test using the HttpServer
class, but I get 500 responses from the server and no information to debug the problem.
Is there a way to create a unit tests for the routing of an ASP.NET Web API site?
Ideally, I'd like to create a request using HttpClient
and have the server handle the request and pass it through the expected routing process.
I have written a blog post about testing routes and doing pretty much what you are asking about:
http://www.strathweb.com/2012/08/testing-routes-in-asp-net-web-api/
Hope it helps.
Additional advantage is that I used reflection to provide action methods - so instead of using routes with strings, you do add them in a strongly typed manner. With this approach, if your action names ever change, the tests won't compile so you will easily be able to spot errors.
The best way to test your routes for your ASP.NET Web API application is the integration test your endpoints.
Here is simple Integration test sample for your ASP.NET Web API application. This doesn't mainly test your routes but it invisibly tests them. Also, I am using XUnit, Autofac and Moq here.
[Fact, NullCurrentPrincipal] public async Task Returns_200_And_Role_With_Key() { // Arrange Guid key1 = Guid.NewGuid(), key2 = Guid.NewGuid(), key3 = Guid.NewGuid(), key4 = Guid.NewGuid(); var mockMemSrv = ServicesMockHelper .GetInitialMembershipService(); mockMemSrv.Setup(ms => ms.GetRole( It.Is<Guid>(k => k == key1 || k == key2 || k == key3 || k == key4 ) ) ).Returns<Guid>(key => new Role { Key = key, Name = "FooBar" }); var config = IntegrationTestHelper .GetInitialIntegrationTestConfig(GetInitialServices(mockMemSrv.Object)); using (var httpServer = new HttpServer(config)) using (var client = httpServer.ToHttpClient()) { var request = HttpRequestMessageHelper .ConstructRequest( httpMethod: HttpMethod.Get, uri: string.Format( "https://localhost/{0}/{1}", "api/roles", key2.ToString()), mediaType: "application/json", username: Constants.ValidAdminUserName, password: Constants.ValidAdminPassword); // Act var response = await client.SendAsync(request); var role = await response.Content.ReadAsAsync<RoleDto>(); // Assert Assert.Equal(key2, role.Key); Assert.Equal("FooBar", role.Name); } }
There are a few external helpers I use for this test. The one of them is the NullCurrentPrincipalAttribute
. As your test will run under your Windows Identity, the Thread.CurrentPrincipal
will be set with this identity. So, if you are using some sort of authorization in your application, it is best to get rid of this in the first place:
public class NullCurrentPrincipalAttribute : BeforeAfterTestAttribute { public override void Before(MethodInfo methodUnderTest) { Thread.CurrentPrincipal = null; } }
Then, I create a mock MembershipService
. This is application specific setup. So, this will be changed for your own implementation.
The GetInitialServices
creates the Autofac container for me.
private static IContainer GetInitialServices( IMembershipService memSrv) { var builder = IntegrationTestHelper .GetEmptyContainerBuilder(); builder.Register(c => memSrv) .As<IMembershipService>() .InstancePerApiRequest(); return builder.Build(); }
The GetInitialIntegrationTestConfig
method is just initializes my configuration.
internal static class IntegrationTestHelper { internal static HttpConfiguration GetInitialIntegrationTestConfig() { var config = new HttpConfiguration(); RouteConfig.RegisterRoutes(config.Routes); WebAPIConfig.Configure(config); return config; } internal static HttpConfiguration GetInitialIntegrationTestConfig(IContainer container) { var config = GetInitialIntegrationTestConfig(); AutofacWebAPI.Initialize(config, container); return config; } }
The RouteConfig.RegisterRoutes
method basically registers my routes. I also have a little extension method to create an HttpClient
over the HttpServer
.
internal static class HttpServerExtensions { internal static HttpClient ToHttpClient( this HttpServer httpServer) { return new HttpClient(httpServer); } }
Finally, I have a static class called HttpRequestMessageHelper
which has bunch of static methods to construct a new HttpRequestMessage
instance.
internal static class HttpRequestMessageHelper { internal static HttpRequestMessage ConstructRequest( HttpMethod httpMethod, string uri) { return new HttpRequestMessage(httpMethod, uri); } internal static HttpRequestMessage ConstructRequest( HttpMethod httpMethod, string uri, string mediaType) { return ConstructRequest( httpMethod, uri, new MediaTypeWithQualityHeaderValue(mediaType)); } internal static HttpRequestMessage ConstructRequest( HttpMethod httpMethod, string uri, IEnumerable<string> mediaTypes) { return ConstructRequest( httpMethod, uri, mediaTypes.ToMediaTypeWithQualityHeaderValues()); } internal static HttpRequestMessage ConstructRequest( HttpMethod httpMethod, string uri, string mediaType, string username, string password) { return ConstructRequest( httpMethod, uri, new[] { mediaType }, username, password); } internal static HttpRequestMessage ConstructRequest( HttpMethod httpMethod, string uri, IEnumerable<string> mediaTypes, string username, string password) { var request = ConstructRequest(httpMethod, uri, mediaTypes); request.Headers.Authorization = new AuthenticationHeaderValue( "Basic", EncodeToBase64( string.Format("{0}:{1}", username, password))); return request; } // Private helpers private static HttpRequestMessage ConstructRequest( HttpMethod httpMethod, string uri, MediaTypeWithQualityHeaderValue mediaType) { return ConstructRequest( httpMethod, uri, new[] { mediaType }); } private static HttpRequestMessage ConstructRequest( HttpMethod httpMethod, string uri, IEnumerable<MediaTypeWithQualityHeaderValue> mediaTypes) { var request = ConstructRequest(httpMethod, uri); request.Headers.Accept.AddTo(mediaTypes); return request; } private static string EncodeToBase64(string value) { byte[] toEncodeAsBytes = Encoding.UTF8.GetBytes(value); return Convert.ToBase64String(toEncodeAsBytes); } }
I am using Basic Authentication in my application. So, this class has some methods which construct an HttpRequestMessege
with the Authentication header.
At the end, I do my Act and Assert to verify the things I need. This may be an overkill sample but I think this will give you a great idea.
Here is a great blog post on Integration Testing with HttpServer. Also, here is another great post on Testing routes in ASP.NET Web API.
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