Json Request in Unit Test of Controller using MockMvc

Overview

Json Request in Controller test using Spring MockMvc.

Premise

--Use Spring Boot. --The model uses JSR310 (LocalDate, etc.) for the date type.

Method to be tested

@PostMapping(value = "hoge", consumes = MediaType.APPLICATION_JSON_VALUE)
public void hoge(@RequestBody Hoge hoge) {
    System.out.println("hoge");
}

Add Jackson as a dependency

Jackson 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>

Json's request in Unit test

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()),
    )
}

reference

Recommended Posts

Json Request in Unit Test of Controller using MockMvc
Test the response JSON of the REST API created in Spring MVC using AssertJ in MockMvc
Unit test architecture using ArchUnit
Implementation of unit test code
Sample code to unit test a Spring Boot controller with MockMvc
Significance of existence of unit test (self-discussion)
[RSpec] Unit test (using gem: factory_bot)
Confirmation and refactoring of the flow from request to controller in [httpclient]
Introduction memo of automatic test using Jenkins
Test the integrity of the aggregation using ArchUnit ②
[rails] List of actions defined in Controller
Try using JSON format API in Java
Test the integrity of the aggregation using ArchUnit ③
Correspondence of the part where Authentication # getDetails is done in the unit test of spring-security
Test controller with Mock MVC in Spring Boot
Automatic creation of Java unit test result report
Support out of support in docker environment using centos6
Story of test automation using Appium [Android / java]