You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在@BeforeAll方法中使用MockMvc遇执行问题求助

解决集成测试中@BeforeAll方法不执行的问题

问题根源

  1. 混用了JUnit 4的@RunWith(SpringRunner.class)和JUnit 5的@TestInstance注解,两者不兼容,导致PER_CLASS生命周期配置无法生效。
  2. @BeforeAll修饰的方法是private权限,JUnit 5在PER_CLASS模式下无法调用私有方法。

修复步骤

  1. 移除@RunWith(SpringRunner.class)注解:Spring Boot 2.2+版本的@SpringBootTest已自动集成JUnit 5的SpringExtension,无需额外指定运行器。
  2. 修改createExampleResource()方法的访问权限:将private改为public(或直接去掉private,使用默认包访问权限)。
  3. 确保项目依赖包含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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:37:01