@DataJpaTest加载ApplicationContext失败及配置加载疑问
JHipster项目@DataJpaTest测试失败问题解决
问题出在哪?
你把@DataJpaTest和@SpringBootTest同时用在测试类里了,这俩注解完全冲突:
@DataJpaTest是切片测试注解,只负责加载JPA相关核心组件(Repository、EntityManager、嵌入式数据源等),目的就是快速测试Repository,不会加载整个应用的所有Bean。@SpringBootTest是全量集成测试注解,会加载项目里所有配置和Bean,包括和Repository测试无关的AsyncConfiguration这类组件。
错误日志里的NumberFormatException就是因为加载了AsyncConfiguration,但测试环境没加载dev配置文件,${async.max-pool-size}占位符没被解析,直接当成字符串转int失败导致的。
怎么解决?
1. 删除冲突注解
直接删掉测试类里的@SpringBootTest(classes = Application.class),只保留@DataJpaTest和@RunWith(SpringRunner.class)。@DataJpaTest会自动扫描当前包及子包下的Repository和实体类,不需要手动指定主类。
2. 加载必要配置
如果Repository测试依赖dev环境的数据库配置或其他属性,添加@ActiveProfiles("dev")注解,让测试环境加载对应的配置文件,解析占位符。
修正后的测试代码
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertNotNull; @RunWith(SpringRunner.class) @DataJpaTest @ActiveProfiles("dev") public class UserRepositoryTest { @Autowired UserRepository userRepository; @Test public void notNull() { assertNotNull(userRepository); } }
额外提示
如果项目里有自定义JPA配置没被自动加载,可用@Import导入对应的配置类;要是有多余的自动配置类干扰测试,就用@DataJpaTest(excludeAutoConfiguration = ...)排除掉。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

