Spring @WebMvcTest doesn't work with Java 8 types

In a spring boot application, I have a rest controller that accepts a payload that contains a Java 8 type LocalDate

. Also I have this library:

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

      

The controller works fine when called, however the integration test @WebMvcTest

fails in this field with 400 HTTP code and this exception:

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

      

The date of the production call and test call is passed as:

"date":"2017-03-21"

      

if it matters.

Is there a way to make @WebMvcTest

Java8 types work?

+3


source to share


3 answers


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

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

      

This fixed the problem.



EDIT: Works well with simpler configuration (Spring Boot + jackson-datatype-jsr310 library on classpath):

@Bean
@Primary
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    return builder.build()
}

      

+1


source


You must register any converter you have with MockMvcBuilders

, for example:

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

      



Or just (I do it this way) is @Bean

that returns the already configured ObjectMapper

(s ObjectMapper#registerModule(new JavaTimeModule())

) and returns that. This one @Configuration

should be used in your test.

+2


source


As far as java.time.LocalDate is concerned, you can parse / format your LocalDate directly to String, which is then processed into LocalDate using RestControllerMethod:

@RestController
@RequestMapping("/api/datecontroller/")
public class YourDateController{

@GetMapping(value = "myDateMethod/" + "date")
public void yourDateMethod(@PathVariable("date") @DateTimeFormat(pattern="yyyy-MM-dd") final LocalDate date) {
// ... your code ...
    }
}

      

0


source







All Articles