Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring's @WebMvcTest doesn't work with Java 8 types

In the spring boot app I have a rest controller which takes a payload containing a Java 8 type LocalDate. Also I have this library plugged in:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Controller works fine when called however a @WebMvcTest integration test fails on that field with 400 HTTP code and this exception:

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException 

Date in the production call and the test call is passed as:

"date":"2017-03-21"

if that matters.

Is there a way to make @WebMvcTest work with Java8 types?

like image 852
Sergey Pauk Avatar asked Sep 11 '25 18:09

Sergey Pauk


2 Answers

You should register whatever converter you have with MockMvcBuilders, for example:

MockMvcBuilders
        .standaloneSetup(controller)
        .setMessageConverters(converter) // register..
        .build();

Or simply (I do it like this) have a @Bean that returns the already configured ObjectMapper (with ObjectMapper#registerModule(new JavaTimeModule())) and return that. This @Configuration should be used within your test.

like image 82
Eugene Avatar answered Sep 14 '25 08:09

Eugene


Inspired by Eugene's hint added the following bean configuration to the test configuration:

@Bean
@Primary
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    return builder.modules(new JavaTimeModule()).build();
}

That solved the problem.

EDIT: Works fine with a simpler config (Spring Boot + jackson-datatype-jsr310 library in the classpath):

@Bean
@Primary
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    return builder.build()
}
like image 24
Sergey Pauk Avatar answered Sep 14 '25 09:09

Sergey Pauk