Json Request in Controller test using Spring MockMvc.
--Use Spring Boot. --The model uses JSR310 (LocalDate, etc.) for the date type.
@PostMapping(value = "hoge", consumes = MediaType.APPLICATION_JSON_VALUE)
public void hoge(@RequestBody Hoge hoge) {
System.out.println("hoge");
}
Jackson
as a dependencyJackson is used for conversion between Java and Json. Below is an example of Maven.
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.6.1</version>
</dependency>
Below is an example from Spock.
def "Json Post request"() {
setup:
//Convert objects to Json format in Jackson
def hoge = new Hoge();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(hoge);
expect:
mockMvc.perform(MockMvcRequestBuilders
.post('/hoge')
//Content Type setting
.contentType(MediaType.APPLICATION_JSON)
//Json settings
.content(json)
).andExpect(
MockMvcResultMatchers.status().is(HttpStatus.OK.value()),
)
}
Recommended Posts