ElD*_*ino 15 java junit spring-boot
我正在尝试编写我的第一个 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());
}
}
Run Code Online (Sandbox Code Playgroud)
我已经检查过 IntelliJ 的调试器,可以确认 mockMvc 本身为空。因此,所有异常消息告诉我的是“java.lang.NullPointerException”。
我已经尝试为诸如“@SpringBootTest”或“@RunWith(SpringRunner.class)”之类的测试类添加更通用的 Spring Boot 注释,以防它与初始化 Spring 有关但没有运气。
ala*_*mpo 25
奇怪,前提是您也尝试过@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")));
}
}
Run Code Online (Sandbox Code Playgroud)
完整样本在这里
考虑以下有关 @WebMvcTest 和 @AutoConfigureMockMvc 注释的使用的评论也是值得的,如Spring 文档中所述
默认情况下,使用@WebMvcTest 注释的测试还将自动配置 Spring Security 和 MockMvc(包括对 HtmlUnit WebClient 和 Selenium WebDriver 的支持)。为了对 MockMVC 进行更细粒度的控制,可以使用 @AutoConfigureMockMvc 注释。
通常@WebMvcTest 与@MockBean 或@Import 结合使用来创建@Controller bean 所需的任何协作者。
如果您希望加载完整的应用程序配置并使用 MockMVC,则应考虑将 @SpringBootTest 与 @AutoConfigureMockMvc 结合使用,而不是此注释。
使用 JUnit 4 时,此注解应与 @RunWith(SpringRunner.class) 结合使用。
接受的答案有效,但是我也解决了问题而没有导入@RunWith(SpringRunner.class).
就我而言,我导入了org.junit.Test而不是较新的org.junit.jupiter.api.Test.
如果你使用 Maven,你可以避免犯这个排除junit-vintage-engine依赖的错误spring-boot-starter-test:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12103 次 |
| 最近记录: |