Skip to content

Commit f05bf46

Browse files
authored
BAEL-8522: Specifying Default Value with MapStruct (#17767)
1 parent cfd55dd commit f05bf46

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@ public interface PersonMapper {
1313
PersonMapper INSTANCE = Mappers.getMapper(PersonMapper.class);
1414

1515
@Mapping(target = "id", source = "person.id", defaultExpression = "java(java.util.UUID.randomUUID().toString())")
16+
@Mapping(target = "name", source = "person.name", defaultValue = "anonymous")
1617
PersonDTO personToPersonDTO(Person person);
1718
}

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

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
package com.baeldung.mapper;
22

3-
import static org.junit.Assert.assertEquals;
4-
import static org.junit.Assert.assertNotNull;
5-
import static org.junit.Assert.assertNull;
6-
7-
import org.junit.Test;
8-
93
import com.baeldung.dto.PersonDTO;
104
import com.baeldung.entity.Person;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.*;
118

129
public class PersonMapperUnitTest {
1310

@@ -23,4 +20,16 @@ public void givenPersonEntitytoPersonWithExpression_whenMaps_thenCorrect() {
2320
assertNotNull(personDto.getId());
2421
assertEquals(personDto.getName(), entity.getName());
2522
}
23+
24+
@Test
25+
public void givenPersonEntityWithNullName_whenMaps_thenCorrect() {
26+
// Given a Person entity with no name set and no ID
27+
Person entity = new Person();
28+
entity.setId("1"); // Explicitly setting ID to null for clarity
29+
30+
// When mapping to PersonDTO
31+
PersonDTO personDto = PersonMapper.INSTANCE.personToPersonDTO(entity);
32+
// And the name in PersonDTO should be the default value "anonymous"
33+
assertEquals("anonymous", personDto.getName());
34+
}
2635
}

0 commit comments

Comments
 (0)