using AutoMapper;
using NUnit.Framework;
namespace ClassLibrary3
{
public class Tests
{
private IMapper mapper;
[SetUp]
public void SetUp()
{
var configuration = new MapperConfiguration(with => with.AddProfile<Mapper>());
mapper = configuration.CreateMapper();
}
[Test]
public void ItMapsLastChanged()
{
var foo = GetSource();
var result = mapper.Map<Flat>(foo);
Assert.That(result.LastChanged, Is.EqualTo("today"));
}
[Test]
public void ItShouldMapIsSystemData()
{
var foo = GetSource();
var result = mapper.Map<Flat>(foo);
Assert.That(result.IsSystemData, Is.True);
}
private static Foo GetSource()
{
return new Foo
{
LastChanged = "today",
Bar = new Bar { IsSystemData = true }
};
}
}
public class Foo
{
public string LastChanged { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
public bool IsSystemData { get; set; }
}
public class Flat
{
public string LastChanged { get; set; }
public bool IsSystemData { get; set; }
}
public class Mapper : Profile
{
public Mapper()
{
// *** works, but feels clunky
//CreateMap<Foo, Flat>()
// .AfterMap((foo, flat, context) => context.Mapper.Map(foo.Bar, flat));
//CreateMap<Bar, Flat>();
// *** works, but seems very coupled (foo to bar) :(
//CreateMap<Foo, Flat>()
// .ForMember(dest => dest.IsSystemData, _ => _.MapFrom(src => src.Bar.IsSystemData));
// *** doesn't work, but seems to be the nicest
CreateMap<Foo, Flat>();
CreateMap<Bar, Flat>();
}
}
}