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

JUnit5中@BeforeEach注解方法未执行引发空指针异常求助

解决JUnit 5 @BeforeEach方法未执行导致NullPointerException的问题

看起来你遇到的核心问题是JUnit 5的@BeforeEach初始化方法完全没被触发,导致测试字段s始终为null,进而抛出NPE。你的测试代码本身语法上是正确的,所以问题大概率出在依赖配置或者测试运行环境上,下面是几个排查和解决的方向:

1. 检查Maven依赖是否正确引入JUnit 5

JUnit 5和JUnit 4的依赖是完全分离的,如果你的项目里不小心混用了JUnit 4的核心依赖,或者没引入JUnit 5的必要组件,就会导致@BeforeEach这类JUnit 5注解不被识别。

确保你的pom.xml里包含以下依赖(版本可以根据需要调整):

<!-- JUnit 5 API,用于编写测试 -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>
<!-- JUnit 5 引擎,用于运行测试 -->
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>

同时要移除任何JUnit 4的旧依赖,比如:

<!-- 这个是JUnit 4的,要删掉 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>

2. 确认Maven Surefire插件支持JUnit 5

旧版本的Maven Surefire插件不支持JUnit 5,会默认用JUnit 4的方式运行测试,导致JUnit 5注解失效。确保你的插件版本至少是2.22.0,配置示例:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.1.2</version>
        </plugin>
    </plugins>
</build>

3. 检查IDE的测试运行配置

如果你用IDE(比如IntelliJ IDEA、Eclipse)运行测试,要确认运行配置是用JUnit 5而不是JUnit 4:

  • 在IntelliJ里,右键测试类选择"Run"时,确保弹出的配置里"Test runner"是JUnit 5;
  • 如果之前有旧的JUnit 4运行配置,建议删除后重新创建。

4. 排查代码中是否混入JUnit 4注解

如果你的测试类或者父类中不小心加了JUnit 4的@RunWith注解,会强制使用JUnit 4的运行器,导致JUnit 5的@BeforeEach完全不被执行。比如:

// 这个JUnit 4的注解会导致JUnit 5注解失效,要删掉
@RunWith(SpringRunner.class)
public class TestClass {
    // ...
}

验证方法

修改完配置后,执行mvn clean test,如果看到输出里先打印before再打印testing,说明@BeforeEach已经正常执行,NPE问题也会解决。

内容的提问来源于stack exchange,提问作者David

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:41:18