Testing an Owin based application with the CQRS pattern.

The other day I was working for a client on an owin based web-application. In this application they are using the CQRS pattern which is running on MediatR. The application has many depencies which are being registered and loaded using Autofac.
They were also using the IAppbuilder of Owin the initialse all middleware for there application.

The problem I was having, was the fact that I couldn’t easly test my fresh created commands because I had some problems in creating a clean and easy way to use Owin for configuring the dependencies.
Because I wanted to re-use the already existing ConfigureDependencies operation. (because otherwise I needed to created a new place for configurtions) That would not be an option, since this is easly forgotten when introducing new dependecies.
This application has many depencies and configurations since it is using stuff like MediatR, Autofac (constructor injection, method injection), AutoMapper, Owin, etc.. And all these things need complex configurations in order to work correctly.

Then I found out about the TestServer of the Owin.Testing lib. https://docs.microsoft.com/en-us/previous-versions/aspnet/dn782655(v%3Dvs.113)

That seemed to be very usefull. So I made my own customstartup class. which I then used in the Testserver. Like this

this.customStartup = new CustomStartup();
this.action = new Action<IAppBuilder>(this.customStartup.Configuration);

And here is my startup class

public class CustomStartup
       public IContainer Container { get; set; }
       public void Configuration(IAppBuilder app)
           var containerBuilder = new ContainerBuilder();
           WebApiConfig.ConfigureDependencies(containerBuilder, app);
           this.Container = containerBuilder.Build();

This worked out perfectly for me. So the only thing I needed to was building my container and Iside that container I had all my stuff. Automapper profiles, MediatR modules, Dependencies, everything.


using(var server = TestServer.Create(this.action))
        var mediator = this.customStartup.Container.Resolve<IMediator>();

Leave a Reply