如何使用Spring Boot @JdbcTest切片测试Repository且不加载完整应用上下文
实现方案
你要的轻量化Repository测试可以通过@JdbcTest+禁用内置测试数据库+仅导入目标Bean的组合实现,完全不需要加载完整应用上下文,也不需要自定义ContextLoader,符合Spring Boot 2.4.6版本的原生支持逻辑。
核心实现代码示例
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest; import org.springframework.context.annotation.Import; import org.springframework.jdbc.core.JdbcTemplate; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.junit.jupiter.api.Assertions.assertEquals; @JdbcTest // 关键:不替换application.yaml中配置的数据源,使用你项目实际的数据库配置 @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // 仅导入需要测试的Repository,不会加载其他无关的Service、Controller、消息队列等Bean @Import(MyRepository.class) public class MyRepositoryTest { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private MyRepository myRepository; @Test void testComplexSql() { // 准备测试数据 jdbcTemplate.update("INSERT INTO your_table(field1, field2) VALUES (?, ?)", "test", 1); // 执行待测试逻辑 var result = myRepository.yourComplexQueryMethod("test"); // 验证结果 assertEquals(1, result.size()); } }
多Repository测试优化
如果需要同时测试多个Repository,可以单独定义测试配置类统一注册需要的Bean,避免每个测试类重复导入:
import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcTemplate; @TestConfiguration public class RepositoryTestConfig { @Bean public MyRepository myRepository(JdbcTemplate jdbcTemplate) { return new MyRepository(jdbcTemplate); } @Bean public OtherRepository otherRepository(JdbcTemplate jdbcTemplate) { return new OtherRepository(jdbcTemplate); } }
测试类中将@Import(MyRepository.class)替换为@Import(RepositoryTestConfig.class)即可。
额外说明
- 如果是JPA Repository测试,将
@JdbcTest替换为@DataJpaTest即可,其他配置逻辑完全一致 - 测试默认开启事务自动回滚,不会污染正式数据库数据,无需手动清理测试数据
- 该方案只会加载JDBC相关核心组件(数据源、事务管理器、JdbcTemplate)和你主动导入的Bean,上下文加载速度远快于
@SpringBootTest的全量加载
内容的提问来源于stack exchange,提问作者Julian
相关产品推荐
相关产品推荐

