|
| 1 | +package com.fasterxml.jackson.datatype.jsr310; |
| 2 | + |
| 3 | +import static org.hamcrest.core.IsEqual.equalTo; |
| 4 | +import static org.junit.Assert.assertThat; |
| 5 | +import static org.junit.internal.matchers.StringContains.containsString; |
| 6 | + |
| 7 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 8 | +import com.fasterxml.jackson.databind.module.SimpleModule; |
| 9 | +import com.fasterxml.jackson.datatype.jsr310.deser.YearMonthDeserializer; |
| 10 | +import com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer; |
| 11 | +import org.junit.Test; |
| 12 | +import org.junit.runner.RunWith; |
| 13 | +import org.junit.runners.Parameterized; |
| 14 | +import org.junit.runners.Parameterized.Parameters; |
| 15 | + |
| 16 | +import java.time.YearMonth; |
| 17 | +import java.time.format.DateTimeFormatter; |
| 18 | +import java.util.ArrayList; |
| 19 | +import java.util.Collection; |
| 20 | + |
| 21 | +@RunWith(Parameterized.class) |
| 22 | +public class TestYearMonthSerializationWithCustomFormatter { |
| 23 | + private final DateTimeFormatter formatter; |
| 24 | + |
| 25 | + public TestYearMonthSerializationWithCustomFormatter(DateTimeFormatter formatter) { |
| 26 | + this.formatter = formatter; |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void testSerialization() throws Exception { |
| 31 | + YearMonth dateTime = YearMonth.now(); |
| 32 | + assertThat(serializeWith(dateTime, formatter), containsString(dateTime.format(formatter))); |
| 33 | + } |
| 34 | + |
| 35 | + private String serializeWith(YearMonth dateTime, DateTimeFormatter formatter) throws Exception { |
| 36 | + ObjectMapper mapper = new ObjectMapper().registerModule(new SimpleModule().addSerializer(new YearMonthSerializer(formatter))); |
| 37 | + return mapper.writeValueAsString(dateTime); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void testDeserialization() throws Exception { |
| 42 | + YearMonth dateTime = YearMonth.now(); |
| 43 | + assertThat(deserializeWith(dateTime.format(formatter), formatter), equalTo(dateTime)); |
| 44 | + } |
| 45 | + |
| 46 | + private YearMonth deserializeWith(String json, DateTimeFormatter formatter) throws Exception { |
| 47 | + ObjectMapper mapper = new ObjectMapper().registerModule(new SimpleModule().addDeserializer(YearMonth.class, new YearMonthDeserializer(formatter))); |
| 48 | + return mapper.readValue("\"" + json + "\"", YearMonth.class); |
| 49 | + } |
| 50 | + |
| 51 | + @Parameters |
| 52 | + public static Collection<Object[]> customFormatters() { |
| 53 | + Collection<Object[]> formatters = new ArrayList<>(); |
| 54 | + formatters.add(new Object[]{DateTimeFormatter.ofPattern("uuuu-MM")}); |
| 55 | + return formatters; |
| 56 | + } |
| 57 | +} |
0 commit comments