首页 > 解决方案 > 在 Junit mockMVC 中模拟空对象

问题描述

我正在尝试将 null 作为 JUnit mockMvc 的内容类型传递,但它失败了

Object obj =null;
MvcResult result = mockMvc.perform(post("/mgr/v1/processEvent")
    .contentType(MediaType.APPLICATION_JSON)
    .content(String.valueOf(obj))
    .accept(MediaType.APPLICATION_JSON))
    .andDo(print())
    .andExpect(status().is4xxClientError()).andReturn();

它不会进入控制器调用

请帮忙

标签: javaspring-bootmockmvc

解决方案


不要使用String.valueOf(null);. Null 被解释为导致NullpointerException. 只需使用空字符串或留下完整的行。

MvcResult result = mockMvc.perform(post("/mgr/v1/processEvent")
    .contentType(MediaType.APPLICATION_JSON)
    .accept(MediaType.APPLICATION_JSON))
    .andDo(print())
    .andExpect(status().is4xxClientError()).andReturn();

推荐阅读