gpt4 book ai didi

java - Spring Boot MVC 测试 - MockMvc 始终为空

转载 作者:行者123 更新时间:2023-12-01 11:00:51 36 4
gpt4 key购买 nike

我正在尝试编写我的第一个 Spring MVC 测试,但我无法让 Spring Boot 将 MockMvc 依赖项注入(inject)我的测试类。这是我的课:

@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 有关但没有运气。

最佳答案

奇怪,前提是您也尝试过 @RunWith(SpringRunner.class)@SpringBootTest .您是否也尝试过 @AutoConfigureMockMvc注解?下面的示例工作正常。

@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")));
}
}
完整样本 here
关于@WebMvcTest 和@AutoConfigureMockMvc 注释的用法,还值得考虑以下评论,详见 Spring's documentation

By default, tests annotated with @WebMvcTest will also auto-configure Spring Security and MockMvc (include support for HtmlUnit WebClient and Selenium WebDriver). For more fine-grained control of MockMVC the @AutoConfigureMockMvc annotation can be used.

Typically @WebMvcTest is used in combination with @MockBean or @Import to create any collaborators required by your @Controller beans.

If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest combined with @AutoConfigureMockMvc rather than this annotation.

When using JUnit 4, this annotation should be used in combination with @RunWith(SpringRunner.class).

关于java - Spring Boot MVC 测试 - MockMvc 始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59534247/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com