Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using Microsoft.VisualStudio.TestTools.UnitTesting;
using EasyMapper;
using System;
using System.Diagnostics;
namespace Test
{
[TestClass]
public class EasyMapperTest
{
//
// Check the class Person and PersonViewModel below
// to understand how custom mapping works
//
[TestMethod]
public void TestMapper()
{
Person person = GetTestPerson();
// Person to PersonViewModel
PersonViewModel personViewModel = person.To<PersonViewModel>();
Assert.AreEqual(person.Name, personViewModel.FullName);
Assert.AreEqual(person.Id, personViewModel.Id);
// Reverse (PersonViewModel to Person)
Person personAgain = personViewModel.To<Person>();
Assert.AreEqual(personViewModel.FullName, personAgain.Name);
Assert.AreEqual(personViewModel.Id, personAgain.Id);
// person and personAgain are two separate instances of
// Person class with similiar values.
// You do not need the Alias attribute on both sides.
// Ignore certain properties
//
// Person to Person but ignore Id and Name property
Person personIgnored = person.To<Person>(nameof(Person.Id), nameof(Person.Name));
Assert.AreEqual(0, personIgnored.Id);
Assert.IsNull(personIgnored.Name);
// Only address has been copied
Assert.AreEqual(person.Address, personIgnored.Address);
}
[TestMethod]
public void TestCopy()
{
var person = GetTestPerson();
var anotherPerson = GetTestPerson();
anotherPerson.Address = "Changed";
Assert.AreNotEqual(person.Address, anotherPerson.Address);
person.CopyTo(anotherPerson);
Assert.AreEqual(person.Address, anotherPerson.Address, false);
}
[TestMethod]
public void TestWhiteListOrBlackList()
{
var person = GetTestPerson();
var person2 = person.ToUsingWhiteList<PersonViewModel>(nameof(Person.Name));
Assert.AreEqual(0, person2.Id);
Assert.AreEqual(person.Name, person2.FullName);
var person3 = new PersonViewModel { Id = 1 };
person.CopyToUsingWhiteList(person3, nameof(Person.Name));
Assert.AreEqual(1, person3.Id);
Assert.AreEqual(person.Name, person3.FullName);
}
[TestMethod]
public void TestTypeMismatch()
{
var person = GetTestPerson();
var personViewModel = person.To<PersonViewModel2>();
// PersonViewModel2.Id is string where as Person.Id is int
Assert.IsNull(personViewModel.Id);
Assert.AreEqual(person.Name, personViewModel.Name);
}
public static Person GetTestPerson()
{
return new Person
{
Id = 10,
Name = "Mustakim",
Address = "London"
};
}
}
public class PersonViewModel
{
public int Id {get; set;}
[Alias("Name")]
// Or [Alias("Name", "Address", ...)]
public string FullName {get; set;}
}
public class PersonViewModel2
{
public string Id {get; set;}
public string Name {get; set;}
}
public class Person
{
public int Id {get; set;}
public string Name {get; set;}
public string Address {get; set;}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.