【发布时间】:2020-04-19 09:37:48
【问题描述】:
我正在尝试编写我的第一个 Spring MVC 测试,但我无法让 Spring Boot 将 MockMvc 依赖项注入我的测试类。这是我的课:
@WebMvcTest
public class WhyWontThisWorkTest {
private static final String myUri = "uri";
private static final String jsonFileName = "myRequestBody.json";
@Autowired
private MockMvc mockMvc;
@Test
public void iMustBeMissingSomething() throws Exception {
byte[] jsonFile = Files.readAllBytes(Paths.get("src/test/resources/" + jsonFileName));
mockMvc.perform(
MockMvcRequestBuilders.post(myUri)
.content(jsonFile)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
}
}
我检查过 IntelliJ 的调试器,可以确认 mockMvc 本身为空。因此,所有异常消息告诉我的是“java.lang.NullPointerException”。
我已经尝试为“@SpringBootTest”或“@RunWith(SpringRunner.class)”等测试类添加更通用的 Spring Boot 注释,以防它与初始化 Spring 有关但没有运气。
【问题讨论】:
-
你能提供你的 pom 或 gradle 文件吗?
标签: java spring-boot junit