为何@SpringBootTest注入House Bean的单元测试失败?
测试失败原因及解决方案
核心问题:JUnit版本与Spring Boot版本不兼容
Spring Boot 1.5.x(配套Spring 4.3.x)仅支持JUnit 4,但你使用了JUnit 5(5.10.1),两者的测试框架机制完全不兼容,导致@SpringBootTest无法正常初始化Spring上下文,最终@Autowired的House实例始终为null。
具体原因
Spring Boot 1.5.x的测试依赖是基于JUnit 4设计的,它识别的是JUnit 4的@Test注解(org.junit.Test)和运行逻辑。而你代码中用的是JUnit 5的@Test(org.junit.jupiter.api.Test),Spring Boot 1.5.x无法识别这个注解,测试运行时根本没有触发Spring上下文的初始化流程,自然不会实例化和注入House Bean。
你之前尝试添加@SpringBootTest(classes = {House.class})无效,也是因为测试上下文根本没启动,指定类列表也不会被处理。
解决方案
方案1:降级JUnit到4.x(推荐,匹配现有Spring Boot版本)
将JUnit依赖替换为JUnit 4.12(Spring Boot 1.5.x的默认兼容版本),同时修改测试类中的注解和断言:
@SpringBootTest public class SpringContextTest{ @Autowired House house; // 使用JUnit 4的@Test注解 @org.junit.Test public void houseBeanShouldNotBeNull(){ // 使用JUnit 4的断言 org.junit.Assert.assertNotNull(house); } }
方案2:升级Spring Boot到支持JUnit 5的版本
如果项目允许升级,将Spring Boot升级到2.2.x及以上版本(对应Spring 5.x及以上),这类版本全面支持JUnit 5,无需修改JUnit版本即可正常运行测试。
内容的提问来源于stack exchange,提问作者Archibald
相关产品推荐
相关产品推荐

