SpringJUnit4ClassRunner运行Spring Boot测试时无法读取properties文件求助
解决Spring Boot测试无法读取application.properties的问题
你的测试类目前使用的是普通Spring测试的@ContextConfiguration和@RunWith(SpringJUnit4ClassRunner.class),这组注解不会自动触发Spring Boot的配置加载机制,所以test/resources下的application.properties没被读取。而其他测试能正常加载,大概率是因为它们用了Spring Boot专门的测试注解。
下面是两种可行的解决方法:
方法一:改用Spring Boot官方推荐的@SpringBootTest(推荐)
直接替换掉现有注解,@SpringBootTest会自动处理Spring Boot的上下文初始化,包括加载test/resources下的application.properties,同时也会帮你完成组件扫描和依赖注入:
@SpringBootTest(classes = SpringBootExampleConfig.class) public class SpringBootExampleTest { @Autowired private IMapper mapper; @Test public void test() { } // 如果内部的SpringTestConfig不是必须的,可以考虑移除 // 因为@SpringBootTest已经会根据指定的配置类和包路径完成组件扫描 }
方法二:手动指定加载配置文件(适合不想用@SpringBootTest的场景)
如果你想保留原有的测试注解结构,可以添加@PropertySource注解手动指定要加载的properties文件,同时确保上下文配置包含你的内部配置类:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {SpringBootExampleConfig.class, SpringTestConfig.class}) @PropertySource("classpath:application.properties") // 显式指定加载配置文件 public class SpringBootExampleTest { @Autowired private IMapper mapper; @Test public void test() { } @Configuration @ComponentScan(basePackageClasses = SpringBootExampleTest.class) public static class SpringTestConfig { } }
需要注意的是,@PropertySource默认只会加载一次,如果你的配置文件有profile相关的后缀(比如application-dev.properties),可能需要结合@ActiveProfiles注解来指定激活的环境。
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

