【记录】用JUnit 4的@Test注解时报错java.lang.NullPointerException的原因与解决方法

项目场景:

在练习黑马点评的逻辑过期解决缓存击穿时,编写了一个预热缓存数据的单元测试

java 复制代码
@SpringBootTest
public class HmDianPingApplicationTests {

    @Resource
    private ShopServiceImpl shopService;
    @Test
    public void testSaveShop() throws InterruptedException {
        shopService.saveShop2Redis(1L,10L);
    }
    }

运行时报空指针异常

bash 复制代码
java.lang.NullPointerException: Cannot invoke "com.hmdp.service.impl.ShopServiceImpl.saveShop2Redis(java.lang.Long, java.lang.Long)" because "this.shopService" is null

原因分析:

这是由于选择的@Test注解选错了,应该选择org.junit.jupiter.api的那一个而不是org.junit的那一个。前者对应JUnit 5单元测试框架 后者对应JUnit 4单元测试框架。两者的对比如下:

JUnit 4: org.junit.Test

  • 用途 : JUnit 4 提供的基础单元测试注解,用于标记测试方法。

  • 特点: 不支持重复测试、参数化测试等高级功能(需要额外扩展)。

  • 测试方法必须是 public 的。(这也是为什么如果用了这个注解,测试方法没加public的话就没有启动运行的绿色箭头的原因)

  • 必须配合 JUnit 4 的测试运行器使用(如 @RunWith)。

JUnit 5: org.junit.jupiter.api.Test

  • 用途: JUnit 5(JUnit Jupiter)提供的现代化测试注解,是 JUnit 的全新版本。

  • 特点: 无需方法是public(包级权限或 protected 也可)。

  • 支持更多功能,如重复测试(@RepeatedTest)、参数化测试(@ParameterizedTest)。

    更强的扩展性,支持条件测试(如 @EnabledIf)。

  • 无需 @RunWith,改用 @ExtendWith 或直接支持 Spring的测试环境。

JUnit 4 中,Spring 和测试的整合依赖于 @RunWith(SpringRunner.class)(或较早的 SpringJUnit4ClassRunner)。

如果没有添加 @RunWith(SpringRunner.class) 注解,Spring 的测试上下文不会加载,@SpringBootTest 的功能无法生效。

结果是,@Resource(或 @Autowired)的依赖注入不会生效,导致 shopService 为 null。

JUnit 5 使用 SpringExtension(通过 @ExtendWith(SpringExtension.class) 内部实现)来加载 Spring 测试上下文。

@SpringBootTest 会自动应用 SpringExtension,所以无需显式声明 @ExtendWith,Spring 上下文会被正确加载。

因此,在 JUnit 4 中,如果你遗漏了 @RunWith(SpringRunner.class),Spring 的功能不会生效,而在 JUnit 5 中,这一步是自动完成的。

所以为什么 shopService 是 null呢?

bash 复制代码
shopService 的注入依赖于 Spring 容器。如果 Spring 测试上下文没有正确加载:
@Resource 或 @Autowired 不会生效。
导致 shopService 没有被注入,值为 null。
调用 shopService.saveShop2Redis(...) 时自然会抛出 NullPointerException。
在 JUnit 4 中,如果没有正确使用 @RunWith(SpringRunner.class):
Spring 测试上下文未加载,shopService 不会被注入。
这也是为什么用 JUnit 4 会抛出 NullPointerException,而 JUnit 5 不会的根本原因。

解决方案:

方法一 :修复JUnit 4的问题 ,在使用时添加@RunWith(SpringRunner.class)

java 复制代码
@RunWith(SpringRunner.class) // 启用 Spring 的测试功能
@SpringBootTest
public class HmDianPingApplicationTests {

    @Resource
    private ShopServiceImpl shopService;

    @Test
    public void testSaveShop() {
        shopService.saveShop2Redis(1L, 10L);
    }
}

方法二:优先选用JUnit 5的Test注解

相关推荐
小新同学^O^14 分钟前
简单学习 --> WebSocket
java·websocket·网络协议·学习
敲代码的瓦龙43 分钟前
Java?枚举!!!
java·开发语言
NiceCloud喜云1 小时前
IntelliJ IDEA 保姆级安装 + ClaudeAPI 配置教程
java·开发语言·前端·ide·chrome·docker·intellij-idea
2301_815901971 小时前
C#怎么使用协变和逆变 C#泛型中的in和out关键字协变逆变是什么意思怎么用【语法】
jvm·数据库·python
孙6903421 小时前
swf 图片转 pdf
java·后端
用户4682557459131 小时前
Spring AI MCP 实战:tools/list 启动快照陷阱与完整解法
java
m0_463672201 小时前
SQL优化SQL关联查询中的排序字段_减少临时空间占用与内存开销
jvm·数据库·python
吴声子夜歌1 小时前
Java——EnumMap和EnumSet
java·enumset·enummap
gjwjuejin1 小时前
从 Vue 2 到 Vue 3:一位前端工程师的实战学习笔记
java
我叫Double1 小时前
简易版的EINO基于redis库的向量搜索项目v2
数据库·redis·bootstrap