JUnit中HTTP POST请求测试失败(Postman可正常运行)
问题排查与解决方法
1. 修正MockMvc的创建逻辑
你同时使用@SpringBootTest+@AutoConfigureMockMvc自动注入MockMvc,又在setup里手动用standaloneSetup创建实例,这会让控制器脱离Spring上下文,无法注入Service、Repository等依赖,还会丢失自动配置的消息转换器等核心组件。
直接删除手动创建MockMvc的代码,用@Autowired注入的实例即可:
@SpringBootTest @AutoConfigureMockMvc public class ResponseStatusControllerIntegrationTest { @Autowired private MockMvc mockMvc; private String content; @BeforeEach public void setup() { // 移除以下两行代码 // this.mockMvc = MockMvcBuilders.standaloneSetup(new NsaController()) // .build(); try(FileInputStream inputStream = new FileInputStream("\\java\\resources\\post.json")) { content = IOUtils.toString(inputStream); }catch (Exception e){ e.printStackTrace(); } } // ... 测试方法 }
2. 修正POST请求体的传递方式
mockMvc.perform(post("/api/v1/nsascholarship",content))里的第二个参数是用于填充URL路径变量的,不是请求体。正确设置请求体需要用.content(content)方法:
@Test public void endpointTest() throws Exception { this.mockMvc.perform(post("/api/v1/nsascholarship") .contentType(MediaType.APPLICATION_JSON) .content(content)) // 这里才是设置请求体的正确方式 .andExpect(MockMvcResultMatchers.status().isOk()); }
3. 修复JSON文件读取路径
你用的\\java\\resources\\post.json是绝对路径,测试环境中大概率找不到文件,导致content为空,直接触发必填字段缺失的400错误。改用类路径读取文件更可靠:
@BeforeEach public void setup() { try(InputStream inputStream = getClass().getClassLoader().getResourceAsStream("post.json")) { content = IOUtils.toString(inputStream, StandardCharsets.UTF_8); }catch (Exception e){ e.printStackTrace(); } }
确保post.json放在src/test/resources(测试资源目录)或src/main/resources(主资源目录)下。
4. 验证请求体内容
在setup里打印读取到的content,确认JSON内容是否正确加载:
@BeforeEach public void setup() { try(InputStream inputStream = getClass().getClassLoader().getResourceAsStream("post.json")) { content = IOUtils.toString(inputStream, StandardCharsets.UTF_8); System.out.println("读取到的JSON内容:" + content); // 打印验证 }catch (Exception e){ e.printStackTrace(); } }
如果内容为空或格式错误,必然会导致接口返回400。
5. 查看详细错误响应
在测试中添加打印请求和响应的逻辑,获取接口返回的具体错误提示,精准定位缺失的必填字段:
@Test public void endpointTest() throws Exception { this.mockMvc.perform(post("/api/v1/nsascholarship") .contentType(MediaType.APPLICATION_JSON) .content(content)) .andDo(MockMvcResultHandlers.print()) // 打印完整请求响应详情 .andExpect(MockMvcResultMatchers.status().isOk()); }
通过打印的信息能直接看到是哪个字段不符合要求。
内容的提问来源于stack exchange,提问作者Tijunelis
相关产品推荐
相关产品推荐

