Spring实战CDPlayer示例测试报错:Bean未注入且无可用测试方法
错误原因分析
你遇到的两个报错是关联的,核心问题是JUnit版本不匹配导致Spring测试上下文未正常加载,最终依赖注入失败:
No runnable methods是因为测试类混用了JUnit4和JUnit5的注解,运行器无法识别测试方法NullPointerException是因为Spring上下文未启动,@Autowired注解没有生效,cd对象未被注入
解决方案
方案1:适配Spring Boot默认的JUnit5(推荐)
当前Spring Boot官方默认使用JUnit5作为测试框架,修改测试类代码适配即可:
- 替换JUnit4相关注解,使用JUnit5的扩展注解
- 确保
@Test导入的是JUnit5的包路径
修改后的测试类代码如下:
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertNotNull; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = CDPlayerConfig.class) public class CDPlayerTest { @Autowired private CompactDisc cd; @Test public void cdShouldNotBeNull() { assertNotNull(cd); cd.play(); } }
方案2:保留JUnit4写法
如果要沿用《Spring in Action 第四版》里的JUnit4写法,需要手动添加JUnit4依赖:
- 如果你用Maven,在pom.xml中添加以下依赖:
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency>
- 确保测试类中
@Test导入的是org.junit.Test包,不要错导成JUnit5的Test注解。
额外检查项
完成上述配置后如果依然报空指针,检查你的CDPlayerConfig配置类:
- 有没有添加
@ComponentScan注解,扫描到CompactDisc实现类所在的包 - 或者有没有手动编写
@Bean方法,将CompactDisc的实现类注册为Spring容器的Bean
内容的提问来源于stack exchange,提问作者ChunkyLover53
相关产品推荐
相关产品推荐

