无@SpringBootApplication的SpringBoot核心项目JUnit测试报错求助
解决Core模块JUnit测试找不到@SpringBootConfiguration的问题
问题根源
Core模块作为依赖被Rest模块引入,自身没有标注@SpringBootApplication的启动类(该注解仅存在于Rest模块),导致Spring Boot测试框架运行测试时无法自动识别配置上下文,从而抛出Unable to find a @SpringBootConfiguration异常。
解决方案
针对不同测试场景,提供以下几种可行方案:
方案1:创建测试专用配置类
在Core模块的测试目录下,新建一个配置类,扫描Core模块的Repository和Entity,并配置必要的Bean:
@Configuration @EnableJpaRepositories(basePackages = "core.repository") // 扫描Core的Repository包 @EntityScan(basePackages = "core.entity") // 扫描Core的实体类包 @EnableTransactionManagement public class CoreTestConfig { // 配置嵌入式H2数据库用于测试,可按需替换为其他数据源 @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .build(); } }
然后在测试类中指定该配置类:
@RunWith(SpringRunner.class) @DataJpaTest // 针对Repository层的专用测试注解 @ContextConfiguration(classes = CoreTestConfig.class) public class SampleRepositoryTests { @Autowired private SampleRepository sampleRepository; // 编写测试用例 @Test public void testSave() { SampleEntity entity = new SampleEntity(); entity.setName("Test"); sampleRepository.save(entity); assertNotNull(entity.getId()); } }
方案2:在测试类中嵌套配置类
如果不想单独创建配置类,可在测试类内部定义静态嵌套的配置类:
@RunWith(SpringRunner.class) @DataJpaTest @ContextConfiguration public class SampleRepositoryTests { @Autowired private SampleRepository sampleRepository; // 静态嵌套配置类,仅当前测试类生效 @Configuration @EnableJpaRepositories(basePackages = "core.repository") @EntityScan(basePackages = "core.entity") @EnableTransactionManagement static class CoreTestConfig { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .build(); } } // 测试方法... }
方案3:测试Service层时指定完整配置
若测试Service层需要完整的Spring上下文,使用@SpringBootTest并指定测试配置类:
@RunWith(SpringRunner.class) @SpringBootTest(classes = CoreTestConfig.class) public class SampleServiceTests { @Autowired private SampleService sampleService; // 测试方法... }
注意事项
- 若Core模块本身已有业务相关的
@Configuration类,可直接复用该类,无需新建测试配置类。 - 嵌入式数据库(如H2)仅用于测试环境,生产环境需使用正式数据源配置。
内容的提问来源于stack exchange,提问作者Subhajit
相关产品推荐
相关产品推荐

