Unit testing OWIN applications using TestServer
Unit testing a OWIN application (pipeline) can be as simple as calling WebApp.Start
You can have this piece of test code in your unit test library and execute the necessary tests. But one drawback with this approach is every time you call WebApp.Start
Microsoft.Owin.Testing package:
This package contains a TestServer which can create an OWIN request processing pipeline and helpers to submit requests to the pipeline as if it is a real server. Requests made with these helpers never hit the network as they are processed directly in memory. Let’s try to implement the above same test using TestServer.
Install the nuget package ‘Microsoft.Owin.Testing’ using the Nuget package manager into your unit test project. Alternatively you can enter this command in the package manager console:
Install-package Microsoft.Owin.Testing
We are going to use TestServer.Create
Requests can also be constructed and submitted with the CreateRequest helper method as below:
Let’s try to simplify the test further by passing in a lamda for the Configuration method instead of a startup class like below:
How it works?
The HttpClient object that the TestServer helpers use has a special OwinHttpMessageHandler that intercepts all the requests made and converts them into OWIN requests. This OWIN request is being fed to the TestServer directly instead of sending it over the network.
Adding your own client side message handlers:
If you would like to add your own HttpMessageHandler(s) on the client side, you can insert them on the client side pipeline. But as I mentioned in the previous section, to have this TestServer working you need to have the special OwinHttpMessageHandler at the end of the HttpClient pipeline. Here is a sample on how to use your own handlers on the client side:
Client code will have to look something like this:
OWIN environment object as a request:
Alternative to using CreateRequest() or HttpClient to send request, you can send an OWIN environment dictionary directly as a request by using the following overload of TestServer.
server.Invoke(yourOwinEnvironmentDictionary);