Damian Hickey

Mostly software and .NET related. Mostly.

Testing your OWIN application

One of the great things about OWIN is the ability to write tests without having any environmental dependencies (i.e. IIS)  or complicated setup with sperate AppDomains (System.Web.Hosting.ApplicationHost).

Given the following contrived OWIN Startup class that returns OK to all requests...

public class Startup
{
	public void Configuration(IAppBuilder appBuilder)
	{
		appBuilder.UseHandler((request, response) =>
			{
				response.StatusCode = 200;
				response.ReasonPhrase = "OK";
			});
	}
}

('UseHandler' is from the Owin.Extensions package which provides a typed wrapper of convenience around the environment dictionary.)

How do we test this?

First add a package reference to Microsoft.Owin.Testing. As of writing it's prerelease, so don't forget the -pre flag.

Then simply create a TestServer to host your OWIN app, and using the supplied HttpClient, invoke a request like you would against any other web site:

[Fact]
public async Task Should_get_OK()
{
	TestServer testServer = TestServer.Create(appBuilder => new Startup().Configuration(appBuilder));
	HttpResponseMessage response = await testServer.HttpClient.GetAsync("/");
	Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

How sweet is that!

Now you can write simple, fast, in-memory, multiple-web-framework acceptence tests. This, to me, is one of the killer features of OWIN.

Browse sample project on github.