1+ package com .baeldung .modelmapper ;
2+
3+ import org .hamcrest .Matchers ;
4+ import org .junit .Before ;
5+ import org .junit .Test ;
6+ import org .modelmapper .ModelMapper ;
7+ import org .modelmapper .TypeToken ;
8+
9+ import java .util .ArrayList ;
10+ import java .util .List ;
11+
12+ import static org .hamcrest .Matchers .equalTo ;
13+ import static org .hamcrest .Matchers .hasItems ;
14+ import static org .hamcrest .Matchers .hasProperty ;
15+ import static org .hamcrest .collection .IsCollectionWithSize .hasSize ;
16+
17+ import static org .junit .Assert .assertNotNull ;
18+ import static org .junit .Assert .assertThat ;
19+
20+
21+ /**
22+ * @sasam0320
23+ * @description
24+ * This class has test methods of mapping Integer to Character list,
25+ * mapping user list to DTO list using MapperUtil generic methods and Converter
26+ */
27+ public class UserMappingTest {
28+
29+ private ModelMapper mapper ;
30+ private List <User > users ;
31+
32+ @ Before
33+ public void init () {
34+
35+ mapper = new ModelMapper ();
36+ mapper .addMappings (new UserPropertyMap ());
37+ users = new ArrayList ();
38+ users .
add (
new User (
"b100" ,
"user1" ,
"[email protected] " ,
"111-222" ,
"USER" ));
39+ users .
add (
new User (
"b101" ,
"user2" ,
"[email protected] " ,
"111-333" ,
"USER" ));
40+ users .
add (
new User (
"b102" ,
"user3" ,
"[email protected] " ,
"111-444" ,
"ADMIN" ));
41+
42+ }
43+
44+ @ Test
45+ public void testMapIntegerList () {
46+
47+ List <Integer > integers = new ArrayList <Integer >();
48+
49+ integers .add (1 );
50+ integers .add (2 );
51+ integers .add (3 );
52+
53+ List <Character > characters = mapper .map (integers , new TypeToken <List <Character >>() {
54+ }.getType ());
55+
56+ assertThat (characters , hasItems ('1' ,'2' ,'3' ));
57+
58+ }
59+
60+ @ Test
61+ public void testMapGenericTypeLists () {
62+
63+ // Mapping lists using generic type methods
64+
65+ List <UserDTO > userDtoList = MapperUtil .mapList (users , UserDTO .class );
66+
67+ assertThat (userDtoList , Matchers .<UserDTO >hasItem (
68+ Matchers .both (hasProperty ("userId" , equalTo ("b100" )))
69+ .
and (
hasProperty (
"email" ,
equalTo (
"[email protected] " )))
70+ .and (hasProperty ("userName" , equalTo ("user1" )))));
71+
72+ // Mapping lists using PropertyMap and Converter
73+
74+ UserList userList = new UserList ();
75+ userList .setUsers (users );
76+ UserListDTO dto = new UserListDTO ();
77+ mapper .map (userList , dto );
78+
79+ assertNotNull (dto );
80+ assertThat (dto , Matchers .hasProperty ("usernames" ));
81+ assertThat (dto .getUsernames (), hasSize (3 ));
82+
83+ }
84+
85+ }
0 commit comments