In this article, I’m going to share the steps I take in order to run integration tests on ASP.NET WebAPI using OWIN/Katana that uses authentication from ASP.NET Identities.
One of the great things about ASP.NET WebAPI 2.0 is that we can self-host the whole application without the need for IIS. This allows us to easily write integration tests, we can have our test runner spin up the web application in memory and throw in memory requests at it.
Prepare WebAPI for testing
First we need to prepare the WebAPI project for in-memory testing.
If you are generating the Help Page from an XML Documentation, instead of uncommenting the SetDocumentationProvider code in HelpPageConfig.cs, change it to this:
This gist shows us setting the provider if path is found. I did not find this file anywhere when using the OWIN TestServer so we could not use DeploymentItem, hence we just not set the provider if not found.
Data Protector and UserTokenProvider
When using ASP.NET Identities, we have to set the UserTokenProvider on the UserManager so we can generate confirmation, password reset tokens and other features that require encrypting user information. When using the OWIN TestServer, it does not seem to automatically set the Data Protection Provider on the App Builder. We are going to bypass all of that and set the UserTokenProvider as EmailTokenProvider on the user manager:
Configuring Integration Test project
In your integration test project, reference the OWIN.Testing nuget package:
PM> Install-Package Microsoft.Owin.Testing
First lets create a base class that will be inherited by all other test classes:
AssemblyInitialize is used for configuring the test server for the lifetime of the test runner.
TestInitialize will be cleaning up and re-seeding the database before every test is executed. We use the same Entity Framework context used by our WebAPI for this operation.
We are referencing assemblies in the referenceLibs method due to some test runners like resharper and the built in one for visual studio does not copy references that are not directly referenced in the test project.
We can then write a test like this:
Very minimal amount of code reqired to create integration tests when using OWIN/Katana. A similar setup can be done for MVC.