Spring单元测试之post请求

1,864 阅读1分钟

使用方式

通过mockmv去请求相应的接口,代码如下:

String result = mockMvc.perform(
  post("/path/to/url")
    .contentType(MediaType.APPLICATION_JSON)
    .content(value))
  .andExpect(status().isOk())
  .andReturn()
  .getResponse()
  .getContentAsString();

此时会报错400,提示

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /path/to/url
       Parameters = {}
          Headers = [Content-Type:"application/json"]
             Body = <no character encoding set>
    Session Attrs = {}

请求体里显示没有相应的字符编码格式。 需要设置相应的字符编码格式:

.characterEncoding("utf-8")

完整示例


@ExtendWith(SpringExtension.class)
@WebMvcTest(GoodsDetailController.class)
class GoodsDetailControllerTest {

  @Autowired
  private MockMvc mockMvc;

  private JacksonTester<BaseResponse<GoosDetailResponse>> json;
  
    @BeforeEach
  void setUp() {
    JacksonTester.initFields(this, new ObjectMapper());
    }
    
    @Test
     public void test() {
            ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
    String value = ow.writeValueAsString(request);

    String result = mockMvc.perform(
      post("/path/to/url")
        .contentType(MediaType.APPLICATION_JSON)
        .content(value))
      .andExpect(status().isOk())
      .andReturn()
      .getResponse()
      .getContentAsString();

    BaseResponse<GoosDetailResponse> response = json.parse(result).getObject();
     }