Skip to content

Commit 30b4830

Browse files
wynnteoWynn Teo
andauthored
Bael 7725 (#18705)
* BAEL-7725 * update to use junit assert --------- Co-authored-by: Wynn Teo <[email protected]>
1 parent a16d961 commit 30b4830

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.baeldung.context;
2+
3+
public class MappingContext {
4+
5+
public String normalizeName(String name) {
6+
return name == null ? null : name.trim()
7+
.toUpperCase();
8+
}
9+
}

mapstruct/src/main/java/com/baeldung/mapper/CustomerDtoMapper.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
package com.baeldung.mapper;
22

3+
import org.mapstruct.AfterMapping;
4+
import org.mapstruct.Context;
35
import org.mapstruct.Mapper;
46
import org.mapstruct.Mapping;
7+
import org.mapstruct.MappingTarget;
58

9+
import com.baeldung.context.MappingContext;
610
import com.baeldung.dto.CustomerDto;
711
import com.baeldung.entity.Customer;
812

@@ -12,4 +16,14 @@ public interface CustomerDtoMapper {
1216
@Mapping(source = "firstName", target = "forename")
1317
@Mapping(source = "lastName", target = "surname")
1418
CustomerDto from(Customer customer);
19+
20+
@Mapping(source = "firstName", target = "forename")
21+
@Mapping(source = "lastName", target = "surname")
22+
CustomerDto from(Customer customer, @Context MappingContext context);
23+
24+
@AfterMapping
25+
default void normalize(@MappingTarget CustomerDto dto, @Context MappingContext context) {
26+
dto.setForename(context.normalizeName(dto.getForename()));
27+
dto.setSurname(context.normalizeName(dto.getSurname()));
28+
}
1529
}

mapstruct/src/test/java/com/baeldung/mapper/CustomerDtoMapperUnitTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import org.junit.jupiter.api.Test;
66
import org.mapstruct.factory.Mappers;
77

8+
import com.baeldung.context.MappingContext;
89
import com.baeldung.dto.CustomerDto;
910
import com.baeldung.entity.Customer;
1011

@@ -26,4 +27,15 @@ void testGivenCustomer_mapsToCustomerDto() {
2627
assertEquals(customerDto.getForename(), customer.getFirstName());
2728
assertEquals(customerDto.getSurname(), customer.getLastName());
2829
}
30+
31+
@Test
32+
void givenCustomer_whenMappedUsingContext_thenReturnsFormattedDto() {
33+
Customer customer = new Customer();
34+
customer.setFirstName(" max ");
35+
customer.setLastName(" powers ");
36+
MappingContext context = new MappingContext();
37+
CustomerDto dto = customerDtoMapper.from(customer, context);
38+
assertEquals("MAX", dto.getForename());
39+
assertEquals("POWERS", dto.getSurname());
40+
}
2941
}

0 commit comments

Comments
 (0)