The simple, but real example.
We have a POCO or a DTO User:
using System; public class User { public int ID { get; private set; } public string Name { get; private set; } public string LastName { get; private set; } public int Age { get; private set; } public User WithID(int id) { ID = id; return this; } public User WithName(string name) { Name = name; return this; } public User WithLastName(string lastName) { LastName = lastName; return this; } public User WithAge(int age) { Age = age; return this; } public User() { ID = 0; Name = string.Empty; LastName = string.Empty; Age = 0; } }
We have the mapper:
using System; using AutoMapper; using System.Data; using System.Collections.Generic; public class UserMapper { public IEnumerableMap(DataTable data) { AutoMapper.Mapper.Reset(); AutoMapper.Mapper.CreateMap () .ForMember(t => t.ID, f => f.MapFrom(r => r["IdUser"])) .ForMember(t => t.LastName, f => f.MapFrom(r => r["Last_Name"])); return AutoMapper.Mapper.Map >(data.CreateDataReader()); } }
The Test (I use fluent Assertions):
using System; using System.Linq; using System.Collections.Generic; using System.Data; using Microsoft.VisualStudio.TestTools.UnitTesting; using PruebaAutoMapper; using System.Collections; using FluentAssertions; private DataTable CreateDataTable() { var result = new DataTable(); result.Columns.Add(new DataColumn("IdUser", typeof(int))); result.Columns.Add(new DataColumn("Name", typeof(string))); result.Columns.Add(new DataColumn("Last_Name", typeof(string))); result.Columns.Add(new DataColumn("Age", typeof(int))); result.Rows.Add(1, "NameI", "Last_NameI", 1); result.Rows.Add(2, "NameII", "Last_NameII", 2); result.Rows.Add(3, "NameIII", "Last_NameIII", 3); result.Rows.Add(4, "NameIV", "Last_NameIV", 4); return result; } private IEnumerableCreateList() { var result = new List (); result.Add(new User().WithID(1).WithName("NameI").WithLastName("Last_NameI").WithAge(1)); result.Add(new User().WithID(2).WithName("NameII").WithLastName("Last_NameII").WithAge(2)); result.Add(new User().WithID(3).WithName("NameIII").WithLastName("Last_NameIII").WithAge(3)); result.Add(new User().WithID(4).WithName("NameIV").WithLastName("Last_NameIV").WithAge(4)); return result; } [TestMethod()] public void MapTest() { UserMapper mapper = new UserMapper(); var data = CreateDataTable(); var expected = CreateList(); var actual = mapper.Map(data); expected.ToList().ShouldAllBeEquivalentTo(actual.ToList()); } }
No hay comentarios:
Publicar un comentario