Gulshan
Gulshan

Reputation: 35

Calling @RequestBody from jUnit test in spring

I am new to jUnit test.I have a request to test a method that has a @RequestBody object.Searched for almost 4 hours from goodle but cant find it.I also read similar question from stack but that doesnt solved my problem.

My testing controller:

@Test
public void testInsertRequest() throws Exception {
    mockMvc.perform(post("http://localhost:8081/requests/add"))
            .andExpect(jsonPath("$.date").value("2017-08-09")).andExpect(jsonPath("$.orderPerson").value("Nermin"))
            .andExpect(jsonPath("$.orderPhone").value("0777675432")).andExpect(jsonPath("$.client").value("Nezrin"))
            .andExpect(jsonPath("$.clientPhone").value("0776763254")).andExpect(jsonPath("$.department").value("IT"))
            .andExpect(jsonPath("$.route").value("Neriman Nerimanov"));

}

And method that i want to test:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String insertRequest(@RequestBody EmployeeRequest employeeRequest) {
    System.out.println(employeeRequest.getDate());
    requestService.insertRequest(employeeRequest);   
}

I get this error:Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing.So how can i call from junit @RequestBody

Upvotes: 0

Views: 5958

Answers (1)

Nikolai
Nikolai

Reputation: 785

You should add a request body of the EmployeeRequest type.

EmployeeRequest employeeRequest = new EmployeeRequest(...);
String body = (new ObjectMapper()).valueToTree(employeeRequest).toString();
mockMvc.perform(post("http://localhost:8081/requests/add"))
        .content(body)
        .andExpect ...

Upvotes: 2

Related Questions