MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.32k stars 329 forks source link

Destination and source type mismatch does not seem to be validated #691

Open Ekkeir opened 6 months ago

Ekkeir commented 6 months ago

For the following classes

public class Source
{
    public DateTime Time { get; set; }
}

public class Destination
{
    public int Number { get; set; }
}

I'd expect configuration validation to fail, but we only observe an exception then executing the actual mapping

    [Fact]
    public void Should_Validate_Type_Mapping()
    {
        var config = new TypeAdapterConfig();

        config.ForType<Source, Destination>()
            .Map(dest => dest.Number, source => source.Time);

        // Does not throw
        config.Compile();

        var source = new Source
        {
            Time = DateTime.UtcNow,
        };

        // Actually throws System.InvalidCastException : Invalid cast from 'DateTime' to 'Int32'.
        var result = source.Adapt<Destination>(config);
    }

Is there some kind of configuration switch, that would allow us to validate matched types? We've switched from Automapper and would like to catch invalid mappings without writing tests for all of them.