-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoMapperTest.cs
More file actions
104 lines (91 loc) · 3.21 KB
/
AutoMapperTest.cs
File metadata and controls
104 lines (91 loc) · 3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
using AutoMapper;
using Newtonsoft.Json;
using NUnit.Framework;
namespace AutoMapperTest
{
[TestFixture]
public class AutoMapperTest
{
private IMapper _mapper;
[SetUp]
public void Init()
{
var config = new MapperConfiguration(CreateMap);
_mapper = config.CreateMapper();
}
private void CreateMap(IMapperConfigurationExpression mapperConfigurationExpression)
{
mapperConfigurationExpression
.CreateMap<StudentDto, Student>(MemberList.Destination)
.ForMember(x => x.CreatedOn,
opt => opt.MapFrom(source =>
Convert.ToDateTime(source.Birthday)))
.ForMember(x => x.Teacher,
opt => opt.MapFrom(source =>
JsonConvert.SerializeObject(source.Teacher))); //Check that all destination members are mapped
}
[Test]
public void Test()
{
try
{
var studentDto = GetStudentDto();
//the backend map StudentDto to database entity Student
//and set the value of some property
var student = _mapper.Map<Student>(studentDto);
Assert.AreEqual(studentDto.IdentityId, student.IdentityId);
Assert.AreEqual(studentDto.Name, student.Name);
Assert.AreEqual(studentDto.Birthday, student.Birthday.ToString("yyyy-MM-dd"));
Console.WriteLine(student);
student.Guid = Guid.NewGuid();
student.CreatedBy = "admin";
student.CreatedOn = DateTime.UtcNow;
//then pass the student to database operation helper
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}
/// <summary>
/// frontend pass a dto to backend
/// </summary>
/// <returns></returns>
private StudentDto GetStudentDto()
{
var birthday = new DateTime(1989, 12, 30);
var teacher = GetTeacher();
StudentDto studentDto = new StudentDto
{
IdentityId = "320481198912305142",
Name = "Chuck",
Birthday = birthday.ToString("yyyy-MM-dd"),
Teacher = teacher
};
return studentDto;
}
private Teacher GetTeacher()
{
Teacher teacher = new Teacher();
teacher.IdentityId = "";
teacher.Name = "Joan";
teacher.Birthday = new DateTime(1980, 1, 1);
teacher.Course = "Chinese";
return teacher;
}
[Test]
public void UpdateExistingInstance()
{
//student dto update student
Student student = new Student();
student.Guid = Guid.NewGuid();
Console.WriteLine(student.Guid);
StudentDto studentDto = new StudentDto();
studentDto.IdentityId = "20200924-001";
_mapper.Map(studentDto, student);
Assert.AreEqual(studentDto.IdentityId, student.IdentityId);
}
}
}