membersound
membersound

Reputation: 86845

How to test the @RequestBody of a @RestController with junit?

I want to write a simple test for one of my @RestController and assert that the input @RequestBody has been properly mapped to the PersonDTO:

@RestController
public class PersonServlet {
    @PostMapping("/person") 
    public PersonRsp find(@RequestBody PersonDTO dto) {
        //business logic
    }
}

public class PersonDTO {
    private String firstname, lastname;
}

Question: how can I send a JSON request body to that servlet. And more over inspect the PersonDTO fields that all of them have been correctly set?

It's probably similar to this, but I don't know how to inspect/spy the parsed DTO?

@RunWith(SpringRunner.class)
@WebMvcTest(PersonSerlvet.class)
public class PersonTests {
    @Autowired
    private MockMvc mvc;

    @Test
    public void testExample() throws Exception {
        this.mvc.perform(get("/person"))
                .andExpect(status().isOk());
    }
}

@Duplicate marker: this is not a duplicate of the linked question (which is about how to read the response body string). I'm actually asking for request body testing.

Upvotes: 0

Views: 2576

Answers (1)

tom01
tom01

Reputation: 125

Testing the deserialising of Json to a DTO is not really the responsibility of your Controller, you would be be testing the the underlying object mapper, which is an external library (Jackson, Gson ..??)

Not sure which library is being used but if you want to test your usage of it you would need to manually construct the appropriate object mapper in the similar manner as your application framework and use its api to serialise from the Json String to the Target DTO

Upvotes: 2

Related Questions