Zapnologica
Zapnologica

Reputation: 22556

How to write integration test for asp.net web api

I am busy design a web service with asp.net web api. And I want to start doing unit tests on each controller.

here is my test class so far:

[TestClass]
public class MyDevicesControllerTest
{
    [TestMethod]        
    public void TestValidUser()
    {
        MyDeviceController controller = new MyDeviceController();
        var result = controller.Get();

    }

    [TestMethod]
    public void TestInvalidUser()
    {
        MyDeviceController controller = new MyDeviceController();            
        var result = controller.Get();
    }
}

But my web service makes use of token authentication. So I some how need to emulate the authentication process.

So I was thinking my i not maybe make user of a Http Request to test it? Ie instead of testing the controller I just make a http Request and check its answer?

What is the easier / better way to go about testing it?

Upvotes: 4

Views: 2503

Answers (1)

Mark Seemann
Mark Seemann

Reputation: 233125

In ASP.NET Web API, Authentication happens in the pipeline before the Controllers are invoked, so you'll need to write some Integration Tests for that. I walk you through how to do that in my on-line course on Outside-In TDD, but here's the gist of it:

Here's an Integration Test against a resource using in-memory HTTP requests. This test doesn't use the network:

[Fact]
public void GetReturnsResponseWithCorrectStatusCode()
{
    var baseAddress = new Uri("http://localhost:8765");
    var config = new HttpSelfHostConfiguration(baseAddress);
    config.Routes.MapHttpRoute(
        name: "API Default",
        routeTemplate: "{controller}/{id}",
        defaults: new
        {
            controller = "Home",
            id = RouteParameter.Optional
        });
    var server = new HttpSelfHostServer(config);
    using (var client = new HttpClient(server))
    {
        client.BaseAddress = baseAddress;
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue(
                "Bearer",
                new SimpleWebToken(new Claim("userName", "foo")).ToString());

        var response = client.GetAsync("").Result;

        Assert.True(
            response.IsSuccessStatusCode,
            "Actual status code: " + response.StatusCode);
    }
}

As you can see, it adds a "Bearer" token to the HTTP headers of the request. The SimpleWebToken class is just a custom class I wrote for the occasion, but you can replace it with a better class that creates a correct authentication token.

If you prefer a different authentication scheme (such as Basic or Digest), you can set the Authorization header accordingly.

Upvotes: 7

Related Questions