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

Spring实战CDPlayer示例测试报错:Bean未注入且无可用测试方法

错误原因分析

你遇到的两个报错是关联的,核心问题是JUnit版本不匹配导致Spring测试上下文未正常加载,最终依赖注入失败:

  • No runnable methods 是因为测试类混用了JUnit4和JUnit5的注解,运行器无法识别测试方法
  • NullPointerException 是因为Spring上下文未启动,@Autowired注解没有生效,cd对象未被注入

解决方案

方案1:适配Spring Boot默认的JUnit5(推荐)

当前Spring Boot官方默认使用JUnit5作为测试框架,修改测试类代码适配即可:

  1. 替换JUnit4相关注解,使用JUnit5的扩展注解
  2. 确保@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依赖:

  1. 如果你用Maven,在pom.xml中添加以下依赖:
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
  1. 确保测试类中@Test导入的是org.junit.Test包,不要错导成JUnit5的Test注解。

额外检查项

完成上述配置后如果依然报空指针,检查你的CDPlayerConfig配置类:

  • 有没有添加@ComponentScan注解,扫描到CompactDisc实现类所在的包
  • 或者有没有手动编写@Bean方法,将CompactDisc的实现类注册为Spring容器的Bean

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:06:03