问题描述
我正在尝试编写我的第一个Spring MVC测试,但我只是无法让Spring Boot将MockMvc依赖项注入到我的测试类中.这是我的课程:
I'm trying to write my first Spring MVC test but I just cannot get Spring Boot to inject the MockMvc dependency into my test class. Here is my class:
@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的调试器进行了检查,可以确认嘲笑Mvc本身为空.因此,所有异常消息告诉我的是"java.lang.NullPointerException".
I've checked with IntelliJ's debugger and can confirm that mockMvc itself is null. Thus, all the Exception message tells me is "java.lang.NullPointerException".
我已经尝试为"@SpringBootTest"或"@RunWith(SpringRunner.class)"之类的测试类添加更多常规的Spring Boot注释,以防它与初始化Spring无关,但是没有运气.
I've already tried adding more general Spring Boot annotations for test classes like "@SpringBootTest" or "@RunWith(SpringRunner.class)" in case it has something to do with initializing Spring but no luck.
推荐答案
奇怪,前提是您还尝试过使用 @RunWith(SpringRunner.class)
和 @SpringBootTest
.您是否也尝试过使用 @AutoConfigureMockMvc
批注?下面的示例工作正常.
Strange, provided that you have also tried with @RunWith(SpringRunner.class)
and @SpringBootTest
. Have you also tried with the @AutoConfigureMockMvc
annotation? The sample below is working fine.
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void getHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World of Spring Boot")));
}
}
完整示例此处
也许值得考虑以下有关@WebMvcTest和@AutoConfigureMockMvc注释用法的注释,如 Spring的文档
It may also be worthwhile to consider the following comments regarding the usage of the @WebMvcTest and @AutoConfigureMockMvc annotations as detailed in Spring's documentation
@WebMvcTest通常与@MockBean或@Import结合使用,以创建@Controller bean所需的任何协作者.
Typically @WebMvcTest is used in combination with @MockBean or @Import to create any collaborators required by your @Controller beans.
如果您希望加载完整的应用程序配置并使用MockMVC,则应考虑将@SpringBootTest与@AutoConfigureMockMvc结合使用,而不是此注释.
If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than this annotation.
使用JUnit 4时,此批注应与@RunWith(SpringRunner.class)结合使用.
When using JUnit 4, this annotation should be used in combination with @RunWith(SpringRunner.class).
这篇关于Spring Boot MVC测试-MockMvc始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!