Spring REST Test:没有请求MockHttpServletRequest POST请求的主体

时间:2018-03-08 04:21:51

标签: spring spring-mvc spring-boot

我有一个Junit测试处理Controller类POST的方法。 Junit运行正常。但我没有在日志中看到请求正在为MockHttpServletRequest打印。有人可以解释原因吗?

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")));
}
}

下面打印日志,没有MockHttpServletRequest的请求主体。我在哪里通过JSON" EMPLOYEE_REQUEST"在请求正文中

    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 = []

2 个答案:

答案 0 :(得分:0)

如果您设置字符编码,则请求正文将正确显示。例如:

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {

    if (preference.getKey().equals("switch_show_idle_dialog")) {

        //your code

        return true;
    } else if (preference.getKey().equals("currency_list")) {

        //your code

        return true;
    } else
        return false;
}

答案 1 :(得分:0)

下面是为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();