It’s very common to use AutoMapper to map one object to another. However if not configured, unit testing functions that use AutoMapper will throw a missing mapping exception. I’ve seen in previous projects 2 different approaches developers use AutoMapper. I’m going to show how to configure AutoMapper in unit test for each of the approaches.
Using the singleton instance of the Mapper directly
If in your code, you use AutoMapper.Mapper to map between your objects then in the SetUpFixture of your unit tests, you can configure the mapper as below
[SetUpFixture] public void SetUpFixture() { AutoMapper.Mapper.Initialize(config => { // Add your mapper profile configs or mappings here }); // More setups here }
You will need to reset the mapper configuration in the TearDown if you use [SetUp] instead of [SetUpFixture]
[TearDown] public void TearDown() { AutoMapper.Mapper.Reset(); }
Using the interface IMapper
If you use the interface IMapper from AutoMapper and inject it via constructor (which is my prefer approach), you can configure it in unit tests as below
[SetUp] public void SetUp() { var config = new MapperConfiguration(opts => { // Add your mapper profile configs or mappings here }; var mapper = config.CreateMapper(); // Use this mapper to instantiate your class // More setups here }
You don’t need to reset the mapper because you create a new mapper instance in every test instead of using the same singleton instance. You could use AutoMapper.Mapper from the section above to instantiate your class but you would need to reset it.