在@BeforeAll方法中使用MockMvc遇执行问题求助
解决集成测试中@BeforeAll方法不执行的问题
问题根源
- 混用了JUnit 4的
@RunWith(SpringRunner.class)和JUnit 5的@TestInstance注解,两者不兼容,导致PER_CLASS生命周期配置无法生效。 @BeforeAll修饰的方法是private权限,JUnit 5在PER_CLASS模式下无法调用私有方法。
修复步骤
- 移除
@RunWith(SpringRunner.class)注解:Spring Boot 2.2+版本的@SpringBootTest已自动集成JUnit 5的SpringExtension,无需额外指定运行器。 - 修改
createExampleResource()方法的访问权限:将private改为public(或直接去掉private,使用默认包访问权限)。 - 确保项目依赖包含JUnit 5核心库(如
junit-jupiter-api、junit-jupiter-engine)。
修改后的代码示例
@SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ExampleResourceTest { @Autowired private MockMvc mockMvc; @BeforeAll public void createExampleResource() throws Exception { Map<String, Object> requestBody = new HashMap<>(); requestBody.put("email", "example@email.com"); requestBody.put("username", "example"); requestBody.put("firstName", "Example"); requestBody.put("lastName", "Name"); requestBody.put("password", "@password123"); Gson gson = new Gson(); String json = gson.toJson(requestBody); mockMvc.perform( post("/api/v1/resourcename") .contentType(MediaType.APPLICATION_JSON) .content(json)); } // 其他测试方法... }
内容的提问来源于stack exchange,提问作者Mansehaj Singh
相关产品推荐
相关产品推荐

