|
| 1 | +package com.fasterxml.jackson.datatype.jsr310; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 4 | +import com.fasterxml.jackson.databind.SerializationFeature; |
| 5 | +import com.fasterxml.jackson.databind.module.SimpleModule; |
| 6 | +import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer; |
| 7 | +import org.junit.Test; |
| 8 | +import org.junit.runner.RunWith; |
| 9 | +import org.junit.runners.Parameterized; |
| 10 | +import org.junit.runners.Parameterized.Parameters; |
| 11 | + |
| 12 | +import java.time.ZonedDateTime; |
| 13 | +import java.time.format.DateTimeFormatter; |
| 14 | +import java.util.ArrayList; |
| 15 | +import java.util.Collection; |
| 16 | + |
| 17 | +import static org.junit.Assert.assertThat; |
| 18 | +import static org.junit.internal.matchers.StringContains.containsString; |
| 19 | + |
| 20 | +@RunWith(Parameterized.class) |
| 21 | +public class TestZonedDateTimeSerializationWithCustomFormatter { |
| 22 | + private final DateTimeFormatter formatter; |
| 23 | + |
| 24 | + public TestZonedDateTimeSerializationWithCustomFormatter(DateTimeFormatter formatter) { |
| 25 | + this.formatter = formatter; |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + public void testSerialization() throws Exception { |
| 30 | + ZonedDateTime zonedDateTime = ZonedDateTime.now(); |
| 31 | + assertThat(serializeWith(zonedDateTime, formatter), containsString(zonedDateTime.format(formatter))); |
| 32 | + } |
| 33 | + |
| 34 | + private String serializeWith(ZonedDateTime zonedDateTime, DateTimeFormatter formatter) throws Exception { |
| 35 | + ObjectMapper mapper = new ObjectMapper().registerModule(new SimpleModule().addSerializer( |
| 36 | + new ZonedDateTimeSerializer(formatter))); |
| 37 | + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); |
| 38 | + return mapper.writeValueAsString(zonedDateTime); |
| 39 | + } |
| 40 | + |
| 41 | + @Parameters |
| 42 | + public static Collection<Object[]> customFormatters() { |
| 43 | + Collection<Object[]> formatters = new ArrayList<>(); |
| 44 | + formatters.add(new Object[]{DateTimeFormatter.ISO_ZONED_DATE_TIME}); |
| 45 | + formatters.add(new Object[]{DateTimeFormatter.ISO_OFFSET_DATE_TIME}); |
| 46 | + formatters.add(new Object[]{DateTimeFormatter.ISO_LOCAL_DATE_TIME}); |
| 47 | + formatters.add(new Object[]{DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")}); |
| 48 | + return formatters; |
| 49 | + } |
| 50 | +} |
0 commit comments