Search code examples
unit-testingautomappingfluent-assertions

How to assert if converter is applied on a type using Fluent Assertions


I need to apply some complex logic for creating map so i have used custom type converter as below:

cfg.CreateMap<ConsumerRequest,IEnumerable<ProviderRequest>>().ConvertUsing<RequestConverter>();

I am using fluentassertions in unit testing and want to assert that ConsumerRequest has RequestConverter applied but not sure how to do it, I think I should be able to right an extension method which will assert the same with some message but not sure how to achieve this, any help will be really appreciated.


Solution

  • Created a extension method on IMapper as below:

    public static AutoMapperTypeConverterAssertions<TDestinationModel>ForType<TDestinationModel>(this IMapper subject)
    {
      return new AutoMapperTypeConverterAssertions<TDestinationModel>(subject);
    }
    
    public class AutoMapperTypeConverterAssertions<TDestinationModel> : ReferenceTypeAssertions<object, AutoMapperTypeConverterAssertions<TDestinationModel>>
    {
       public AutoMapperTypeConverterAssertions(object subject)
       {            
         Subject = subject;
       }
    
       protected override string Context => "auto mapper type converter";
    
       public AndConstraint<AutoMapperTypeConverterAssertions<TDestinationModel>> ShouldHaveTypeConverterApplied<TSourceModel, TConverterType>(
        string because = "", params object[] becauseArgs)
       {            
          var mapper = Subject as IMapper;
          var foundTypeInConfig = mapper
            .ConfigurationProvider
            .FindTypeMapFor<TSourceModel, TDestinationModel>()
            .TypeConverterType;
    
          Execute.Assertion
             .BecauseOf(because, becauseArgs)
             .ForCondition(foundTypeInConfig == typeof(TConverterType))
             .FailWith("Expected the mapping for {0} to contain {1} AutoMapper   Type Converter, but was not found.", typeof(TDestinationModel).Name,   typeof(TConverterType).Name);
    
      }
    return new     AndConstraint<AutoMapperTypeConverterAssertions<TDestinationModel>>(this);
    
    
    }