27

I'd like to ask you a question about AutoMapper. We are unit testing our mapping like that:

var dtoFiltrePersonne = new DtoFiltrePersonne { Prop1 = "Test", Prop2 = 1234 };
Mapper.CreateMap<FiltrePersonne, DtoFiltrePersonne>();
var filtrePersonne = DtoAutoMappeur<DtoFiltrePersonne, FiltrePersonne>.Instance.MapFromDtoToEntity(dtoFiltrePersonne);
Assert.AreEqual(dtoFiltrePersonne.Prop1, filtrePersonne.Prop1);
Assert.AreEqual(dtoFiltrePersonne.Prop2, filtrePersonne.Prop2);

I'd like to know if this unit test provides the same coverage?

Mapper.CreateMap<FiltrePersonne, DtoFiltrePersonne>();
AutoMapper.AssertConfigurationIsValid()

I looked into the AutoMapper Configuration documentation and it's not pretty clear for me. Do I need to unit test each mapping or just use the AssertConfigurationIsValid method?

palacsint
  • 28,416
  • 10
  • 82
  • 109
Morgan
  • 343
  • 1
  • 3
  • 9
  • 2
    Important note if using Dependency injection : Don't use the static `Mapper.Configuration.AssertConfigurationIsValid` because it won't work. See this doc for an alternative way to run the assertions: https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection – Simon_Weaver Feb 12 '19 at 19:53
  • @Simon_Weaver, do you have a code example? Can't find the example to enforce AssertConfigurationIsValid for automapper that is used via dependency injection – JeeShen Lee Feb 28 '21 at 06:10
  • 1
    @JeeShenLee Sorry I can't be much help right now. I checked and I literally have AssertConfigurationIsValid commented out! This question may be helpful (some of the answers talk about DI) https://stackoverflow.com/questions/35256008/automapper-migrating-from-static-api – Simon_Weaver Feb 28 '21 at 22:30

1 Answers1

28

It says:

Executing this code produces an AutoMapperConfigurationException, with a descriptive message. AutoMapper checks to make sure that every single Destination type member has a corresponding type member on the source type.

Every single member has correlation with destination type. It may not be the right one (since there are always exception cases), but it at least tests that every property is moved from source type to destination.

Dmitry Reznik
  • 6,812
  • 2
  • 32
  • 27
  • 2
    The really good part about this, is that if you start out with a failing tests, you have to *explicitly handle every case*. I've seen loads of manual tests that verify values on every property of the object, but they are extremely prone to not being updated as the tested classes themselves are. This helps you keep mapping updated over time. – Arve Systad Mar 02 '18 at 14:49
  • To add to this, if your entity is a numeric value and your model is a string, that is probably the wrong data type mapping, but AssertConfigurationIsValid will still pass a unit test. - This bit me today. – John Zabroski Jun 28 '23 at 00:03