Skip to content

Testing WebApi 2 Controllers

April 2, 2014

My most recent project is to create a WebApi for a database. I have been using Asp.net WebApi 2, to create it, and at first it was pretty simple, but I wanted to do some more complicated things and then I ran into a lot of reading and googling (as usual). I have now setup tests for my Web Services using the httpSelfHostServer. This is what is in every controller test class:

      private static System.Uri GetBaseAddress()
        {
            var baseAddress = new Uri("http://localhost:8765");
            return baseAddress;
        }

        private HttpSelfHostServer getServer()
        {
            // Load the controller's DLL (bit of a trick needed to get the server working)
            Type tableControllerType = typeof(TableApi.Controllers.TableController);

            System.Uri baseAddress = GetBaseAddress();
            var config = new HttpSelfHostConfiguration(baseAddress);

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

            // permission required to use the port
            // netsh http add urlacl url=http://+:8765/ user=machine\username
            return new HttpSelfHostServer(config);
        }

Then you can use the server like this in your test itself :

[TestMethod]
public void SectionsKassaNrReturnsElements()
{
     using (HttpSelfHostServer server = getServer())
     {
	server.OpenAsync().Wait();
	HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,
		"http://localhost:8765/Api/Table/?kassanr=1");
	request.Headers.Add("X-ApiKey", "123456");
	using (var client = new HttpClient(server))
	{
        	client.BaseAddress = GetBaseAddress();
		var response = client.SendAsync(request).Result;
		response.EnsureSuccessStatusCode();
		var list =
                  response.Content.ReadAsAsync<IEnumerable<modelSection>>().Result;

		Assert.AreEqual(list.Count(),2,"Actual count : " + list.Count());
	}
     }
}

As you can see I am using an ApiKey header for identification. I have seperate tests for that. If you’d really want to do it according to the rules, you’d need a setting up the database routine as well in your testing class !

Link:

SelfHosted example at asp.net

 

Comments are closed.