0

I have a custom type converter that converts UTC DateTime properties to a company's local time (talked about here: Globally apply value resolver with AutoMapper).

I'd now like to only have this converter do its thing if the property on the view model is tagged with a custom DisplayInLocalTime attribute.

Inside the type converter, if I implement the raw ITypeConvert<TSource, TDestination> interface, I can check if the destination view model property being converted has the attribute:

public class LocalizedDateTimeConverter : ITypeConverter<DateTime, DateTime> 
{
    public DateTime Convert(ResolutionContext context)
    {
        var shouldConvert = context.Parent.DestinationType
                                .GetProperty(context.MemberName)
                                .GetCustomAttributes(false)[0].GetType() == typeof(DisplayInLocalTimeAttribute);
        if (shouldConvert) {
            // rest of the conversion logic...
        }
    }
}

So this code works just fine (obviously there's more error checking and variables in there for readability).

My questions:

  1. Is this the correct way to go about this? I haven't found anything Googling around or spelunking through the AutoMapper code base.
  2. How would I unit test this? I can set the parent destination type on the ResolutionContext being passed in with a bit of funkiness, but can't set the member name as all implementors of IMemberAccessor are internal to AutoMapper. This, and the fact that it's super ugly to setup, makes me this isn't really supported or I'm going about it all wrong.

I'm using the latest TeamCity build of AutoMapper, BTW.

Community
  • 1
  • 1
Darrell Mozingo
  • 865
  • 10
  • 16

1 Answers1

1

Don't unit test this, use an integration test. Just write a mapping test that actually calls AutoMapper, verifying that whatever use case this type converter is there to support works from the outside.

As a general rule, unit tests on extension points of someone else's API don't have as much value to me. Instead, I try to go through the front door and make sure that I've configured the extension point correctly as well.

Jimmy Bogard
  • 26,045
  • 5
  • 74
  • 69
  • I have a question where I was trying to do the same basic thing, but using AutoMapper 10 which doesn't have context.Parent. https://stackoverflow.com/questions/73292263/upgrading-automapper-and-mapping-zero-to-null-based-based-on-an-attribute. Any suggestion on how to use a type converter only if the property has a specific attribute? – jmoreno Aug 10 '22 at 19:45