2

I have a Junit testing a method handling POST of a Controller class. the Junit is running fine. But I dont see in the log Request body being print for the MockHttpServletRequest. Can some one explain why?

package com.spring.batch.learnings.test;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.http.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.hamcrest.Matchers.*;
import org.junit.Before;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.spring.batch.learnings.EmployeeListController;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration
public class EmployeeListControllerTest {

@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;

private final String EMPLOYEE_REQUEST = "[{\"lastName\":\"TESTER\",\"firstName\":\"TONY\"},{\"lastName\":\"NEWBIE\",\"firstName\":\"NICK\"},{\"lastName\":\"INTERMEDIATE\",\"firstName\":\"IAN\"}]";

@Configuration
@EnableAutoConfiguration
public static class Config {
    @Bean
    public EmployeeListController apiController() {
        return new EmployeeListController();
    }
}

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

@Test
public void testupdateEmployees() throws Exception {
    mockMvc.perform(post("/processedEmployeeList")
            .contentType(MediaType.APPLICATION_JSON)
            .content(EMPLOYEE_REQUEST))
            .andDo(print())
            .andExpect(status().isOk())             

            .andExpect(jsonPath("$", hasSize(3)))

            .andExpect(jsonPath("$[0].firstName", is("TONY")))
            .andExpect(jsonPath("$[0].lastName", is("TESTER")))

            .andExpect(jsonPath("$[1].firstName", is("NICK")))
            .andExpect(jsonPath("$[1].lastName", is("NEWBIE")))

            .andExpect(jsonPath("$[2].firstName", is("IAN")))
            .andExpect(jsonPath("$[2].lastName", is("INTERMEDIATE")));
}
}

The log prints below with no request body for MockHttpServletRequest. Where as I am passing a JSON "EMPLOYEE_REQUEST" in the request body

    MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /processedEmployeeList
       Parameters = {}
          Headers = {Content-Type=[application/json]}

Handler:
             Type = com.spring.batch.learnings.EmployeeListController
           Method = public org.springframework.http.ResponseEntity<java.util.List<com.spring.batch.learnings.Employee>> com.spring.batch.learnings.EmployeeListController.updateEmployees(java.util.List<com.spring.batch.learnings.Employee>)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = [{"lastName":"TESTER","firstName":"TONY"},{"lastName":"NEWBIE","firstName":"NICK"},{"lastName":"INTERMEDIATE","firstName":"IAN"}]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
user329551
  • 31
  • 2
  • 5
  • Does this answer your question? [Spring Controller testing with MockMvc post method](https://stackoverflow.com/questions/49956208/spring-controller-testing-with-mockmvc-post-method) – Mike Partridge Dec 27 '19 at 20:17

2 Answers2

1

The request body will appear properly if you set the character encoding. For example:

mockMvc.perform(post("/processedEmployeeList")
        .contentType(MediaType.APPLICATION_JSON)
        .characterEncoding("UTF-8")
        .content(EMPLOYEE_REQUEST))
        .andDo(print())
        .andExpect(status().isOk()) 
Mike Partridge
  • 5,128
  • 8
  • 35
  • 47
0

Below is the example to setup request body for mockMvc

MvcResult result = mockMvc.perform(post( "your url",agreementType)
                    .characterEncoding("UTF-8")
                    .header("key", "value")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content("{ \"key\": \"value\" }"))
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andReturn();
String content = result.getResponse().getContentAsString();