|
| 1 | +package com.baeldung.jackson.miscellaneous.mixin; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; |
| 6 | +import static io.restassured.path.json.JsonPath.from; |
| 7 | +import java.io.IOException; |
| 8 | +import java.util.Optional; |
| 9 | +import static org.assertj.core.api.Assertions.assertThat; |
| 10 | +import org.junit.Test; |
| 11 | + |
| 12 | +public class OptionalTypeTest { |
| 13 | + |
| 14 | + ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module()); |
| 15 | + |
| 16 | + @Test |
| 17 | + public void givenPresentOptional_whenSerializing_thenValueInJson() throws JsonProcessingException { |
| 18 | + |
| 19 | + String subTitle = "The Parish Boy's Progress"; |
| 20 | + Book book = new Book(); |
| 21 | + book.setTitle("Oliver Twist"); |
| 22 | + book.setSubTitle(Optional.of(subTitle)); |
| 23 | + |
| 24 | + String result = mapper.writeValueAsString(book); |
| 25 | + |
| 26 | + assertThat(from(result).getString("subTitle")).isEqualTo(subTitle); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void givenEmptyOptional_whenSerializing_thenNullValue() throws JsonProcessingException { |
| 31 | + |
| 32 | + Book book = new Book(); |
| 33 | + book.setTitle("Oliver Twist"); |
| 34 | + book.setSubTitle(Optional.empty()); |
| 35 | + |
| 36 | + String result = mapper.writeValueAsString(book); |
| 37 | + |
| 38 | + assertThat(from(result).getString("subTitle")).isNull(); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void givenField_whenDeserializingIntoOptional_thenIsPresentWithValue() throws IOException { |
| 43 | + |
| 44 | + String subTitle = "The Parish Boy's Progress"; |
| 45 | + String book = "{ \"title\": \"Oliver Twist\", \"subTitle\": \"" + subTitle + "\" }"; |
| 46 | + |
| 47 | + Book result = mapper.readValue(book, Book.class); |
| 48 | + |
| 49 | + assertThat(result.getSubTitle()).isEqualTo(Optional.of(subTitle)); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + public void givenNullField_whenDeserializingIntoOptional_thenIsEmpty() throws IOException { |
| 54 | + |
| 55 | + String book = "{ \"title\": \"Oliver Twist\", \"subTitle\": null }"; |
| 56 | + |
| 57 | + Book result = mapper.readValue(book, Book.class); |
| 58 | + |
| 59 | + assertThat(result.getSubTitle()).isEmpty(); |
| 60 | + } |
| 61 | +} |
0 commit comments