I have follows object:
@Validated
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@Schema(description = "Request")
public final class Request implements Serializable {
private static final long serialVersionUID = 1L;
@JsonProperty("date")
@Schema(description = "Date")
private OffsetDateTime date;
}
And i send this object as rest-controller's response:
@RestController
public class RequestController {
@RequestMapping(
value = "/requests",
produces = {"application/json;charset=UTF-8"},
consumes = {"application/json"},
method = RequestMethod.POST)
public ResponseEntity<Request> get() {
LocalDate date = LocalDate.of(2021, Month.OCTOBER, 22);
OffsetDateTime dateTime = date.atTime(OffsetTime.MAX);
Request request = new Request(dateTime);
return ResponseEntity.ok(request);
}
}
Yet i have configuration:
@Configuration
public class WebConfiguration implements ServletContextInitializer, WebMvcConfigurer {
private final List<FilterRegistration> filterRegistrations;
private final ApplicationContext applicationContext;
public WebConfiguration(List<RestApplicationInstaller> restApplicationInstallers,
List<MonitoringRestApplicationInstaller> monitoringRestApplicationInstallers,
List<FilterRegistration> filterRegistrations,
ApplicationContext applicationContext) {
this.filterRegistrations = filterRegistrations;
this.applicationContext = applicationContext;
}
@Override
public void onStartup(ServletContext servletContext) {
VersionServletInstaller.installServlets(servletContext, getRegisterAsyncService(servletContext));
filterRegistrations.forEach(filterRegistration -> filterRegistration.onApplicationEvent(new ContextRefreshedEvent(applicationContext)));
}
private RegisterAsyncService getRegisterAsyncService(final ServletContext servletContext) {
final WebApplicationContext ctx = getWebApplicationContext(servletContext);
final RegisterAsyncService registerAsyncService = Objects.requireNonNull(ctx).getBean(RegisterAsyncService.class);
registerAsyncService.exec();
return registerAsyncService;
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer(CustomAnnotationIntrospector customAnnotationIntrospector) {
return builder -> builder.serializationInclusion(NON_NULL)
.annotationIntrospector(customAnnotationIntrospector);
}
}
Ok.
So... I get the date
field in response as:
2021-10-21T23:59:59.999999999-18:00
When i test my controller, i try to get response, deserialize it to Request
object and check matching:
@DirtiesContext
@SpringBootTest(
classes = {WebConfiguration.class, JacksonAutoConfiguration.class},
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension.class)
@EnableWebMvc
class RequestControllerTest {
private static final CharacterEncodingFilter
CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter();
static {
CHARACTER_ENCODING_FILTER.setEncoding(DEFAULT_ENCODING);
CHARACTER_ENCODING_FILTER.setForceEncoding(true);
}
protected MockMvc mockMvc;
@Autowired
protected ObjectMapper objectMapper;
@Autowired
private WebApplicationContext context;
@PostConstruct
private void postConstruct() {
this.mockMvc =
MockMvcBuilders
.webAppContextSetup(this.context)
.addFilters(CHARACTER_ENCODING_FILTER)
.build();
}
@Test
void requestByIdTest() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.post("/requests")
.characterEncoding(CHARACTER_ENCODING_FILTER)
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(
result -> Assertions.assertEquals(mapToObject(result.getResponse().getContentAsString(Charset.forName(CHARACTER_ENCODING_FILTER)), Request.class), getExpectedRequest()));
}
private WebComplianceRequest getExpectedRequest() {
LocalDate date = LocalDate.of(2021, Month.OCTOBER, 22);
OffsetDateTime dateTime = date.atTime(OffsetTime.MAX);
Request request = new Request(dateTime);
}
private <T> T mapToObject(String json, Class<T> targetClass) {
try {
return getReaderForClass(targetClass).readValue(json);
} catch (IOException e) {
throw new RuntimeExsception(e);
}
}
private <T> ObjectReader getReaderForClass(Class<T> targetClass) {
return objectMapper.readerFor(targetClass);
}
}
But i get a exception, because date
field in expected object and in got object are differ:
Date in response: 2021-10-22T17:59:59.999999999Z
Expected date: 2021-10-21T23:59:59.999999999-18:00
Why did this happen?
Why does the Z
appear instead of time zone? Why is the date changed from 2021-10-21
to 2021-10-22
? And how would i can fix it?
I do not get any exception, I get matching failed because dates differ when I match response and expected objects. I just deserialize object with standard ObjectMapper
and check objects matching with equals()
.