WebAPI integration tests with OWIN

WebAPI integration tests with OWIN

owin_tests

Integration test is used for checking the behaviour of application from interface to the database. In our case it will be used with API. It is most useful to:

  • testing if correctly operate on data
  • perform smoke test (checking if some part of API is working)
  • simulate some types of behaviour on API server

Add OWIN into existing app

In this article we will be talking mostly about WebAPI integration tests. In this framework it is very easy to set up it. But first, we should be able to start API server independently. We can use OWIN Katana standalone server functionality. This is a different type of server used in WebAPI. We can still start our API on IIS server, but OWIN gives us an ability to start server in different way.

We can migrate our project to OWIN very easiliy. To do this it is only necessary to add two references and configure server.

So at the beginning add reference following NuGet libraries:

  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.AspNet.WebApi.Owin

OWIN_WebAPI

After this operation, the only thing that left is to configure server. We can do this by defining class and tag it wit proper attribute:

[assembly: OwinStartup(typeof(Owasp.AppSensor.Demo.Api.Startup))]
namespace Owasp.AppSensor.Demo.Api
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration httpConfiguration = new HttpConfiguration();
            WebApiConfig.Register(httpConfiguration);
            app.UseWebApi(httpConfiguration);
        }
    }
}

Attribute OwinStartup can be defined in any place of the project because it is an assembly attribute. It defines which class will be used for Owin configuration. Generally we can assume that Configuration method should do exactly the same as defined in Global.asax Application_Start() method. Moreover Application_Start() method won’t be used any more. the only line necessary for us and different form Global.asax is

app.UseWebApi(httpConfiguration);

It basically configure WebAPI framework to work properly with controllers and its whole pipeline.

At the end we can check if all works fine, just by setting a breakpoint into Configuration method. If it break, OWIN is configured.

Basic API test

When we successfully set up OWIN server, we can start working on integration test. In this case we should also add one library before we write first test. This time we will need:

  • Microsoft.Owin.Testing

Now we can create our test very fast. The whole test can be divided into 3 parts:

  • Arrange (start API server)
  • Act (execute API method)
  • Assert (check result of sent request)

This process can be written shortly:

[Test]
public async Task TestGoodMethod()
{
    using (var server = TestServer.Create<Startup>())
    {
        var result = await server.HttpClient.GetAsync("api/book");
        string responseContent = await result.Content.ReadAsStringAsync();
        var entity = JsonConvert.DeserializeObject<List<string>>(responseContent);

        Assert.IsTrue(entity.Count == 3);
    }
}

First line TestServer.Create<Startup>() starts OWIN server using Startup class as a configuration. It is started on some general localhost address. Then we can easily execute a request against this server. Within TestServer we have access to HttpClient to execute any type of request. As a result we will get a string value of complete HTTP response.

That’s all what we would need to test API methods.

http://www.strathweb.com/2013/12/owin-memory-integration-testing/

Mocking object in test

One interesting aspect of integration API testing is mocking test data inside test server. We can make it in this approach also.

I will describe this mechanism with Dependency Injection library in use, because it helps in mocking data very well. In most cases DI system is configured in Global.asax file. So for OWIN server, the configuration can be placed into Setup.Configuration() method.

We can define virtual method to be able to set up our mocks in tests.

public void Configuration(IAppBuilder app)
{
    HttpConfiguration httpConfiguration = new HttpConfiguration();
    WebApiConfig.Register(httpConfiguration);

    var builder = new ContainerBuilder();
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    builder.RegisterWebApiFilterProvider(config);
    builder.RegisterModule<ServicesDependencyModule>();

    ConfigureIoC(builder);
    var container = builder.Build();
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);


    app.UseWebApi(httpConfiguration);
}

protected virtual void ConfigureIoC(ContainerBuilder builder)
{

}

Thanks to this, we can inherit this class in our test and override ConfigureIoC method to add custom mocks.

public class TestStartup : Startup
{
    protected override void ConfigureIoC(ContainerBuilder builder)
    {
        // set up mocks
        base.ConfigureIoC(builder);
    }
}

More resources:
https://blog.kloud.com.au/2014/10/26/asp-net-web-api-integration-testing-with-one-line-of-code/
http://www.aaron-powell.com/posts/2014-01-12-integration-testing-katana-with-auth.html
http://amy.palamounta.in/blog/2013/08/04/integration-testing-for-asp-dot-net-web-api/

Cover photo