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

使用@JdbcTest测试H2数据库时JdbcTemplate注入为null如何解决?

问题原因及解决方案

核心原因

你遇到的注入为空问题核心是Spring测试上下文未正确启动,结合你给出的代码和配置,具体有几个问题:

1. 测试运行器不匹配

你测试类里用的是JUnit5的@org.junit.jupiter.api.Test注解,但异常栈显示当前Eclipse用的是JUnit4的运行器执行测试:

at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)

JUnit4运行器识别不了JUnit5的测试注解,导致@JdbcTest、@Autowired等Spring注解完全不生效,自然注入的JdbcTemplate就是null。

2. 依赖版本不兼容

Spring Boot 2.0.4 原生适配的JUnit Jupiter版本为5.0.x,你手动指定JUnit Jupiter为5.8.1,和当前Spring Boot版本存在兼容性冲突,也会导致测试上下文加载失败。

3. 自定义Bean未加载(可选)

你注入的Bean名为jdbcTemplateRead,不是Spring Boot自动配置的默认jdbcTemplate,说明你应该是自定义了多数据源和对应JdbcTemplate。而@JdbcTest是切片测试注解,默认只会加载默认数据源、默认JdbcTemplate相关的Bean,你自定义的jdbcTemplateRead不会被扫描到测试上下文里。

修复步骤

方案一:改用JUnit4执行测试(适配当前Spring Boot版本,改动最小)

  1. 把pom.xml里的junit-vintage排除项删掉,恢复JUnit4的支持
  2. 修改测试类的注解,将JUnit5的Test换成JUnit4的,加上Spring运行器注解:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;

@Sql({ "schema.sql", "test-data.sql" })
@JdbcTest
@RunWith(SpringRunner.class)
// 强制激活testing环境,避免Eclipse运行配置不生效
@ActiveProfiles("testing")
// 如果是自定义的jdbcTemplateRead,加上你对应配置类的导入
// @Import(你的Jdbc配置类.class)
public class DbTest {

    @Autowired
    private JdbcTemplate jdbcTemplateRead;

    @Test
    public void testTheDatabase() {
        // 你的测试逻辑
    }
}
  1. 如果你确实是自定义了多数据源的jdbcTemplateRead,可以把@JdbcTest换成@SpringBootTest,加载完整Spring上下文来获取自定义Bean。

方案二:升级Spring Boot版本,用JUnit5执行

  1. 把Spring Boot版本升级到2.5.x及以上,和JUnit 5.8.x兼容
  2. 测试类上补充@ExtendWith(SpringExtension.class)注解(Spring Boot 2.2+之后@JdbcTest已经默认集成,可省略)
  3. 确认Eclipse的测试运行配置选择的是JUnit5,而不是JUnit4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:06:03