Thursday, August 4, 2016

Unit Testing with AutoMapper

If you are using AutoMapper in your projects, you may know that there are multiple ways to use AutoMapper within your application.  There is both static and instance based configuration for AutoMapper.

The most common method of using AutoMapper in most applications is using the Static API.  However, if you are used to using an IoC container such as Ninject, you may consider this problematic when it comes to your Unit Tests, because when you begin executing Unit Tests which depend on the static instance of AutoMapper, you may receive an error such as this:

So how do you work around this exception?

Well, if you are using a Unit Testing framework such as MSTest, the solution is very simple!

You can leverage the [TestInitialize] attribute to initialize your AutoMapper configuration before your Unit Tests execute like so:

Now, when you run your Unit Tests which leverage the static instance of AutoMapper, they should execute without any exceptions or errors!!

No comments:

Post a Comment