Spring Boot 2与JUnit 5测试:如何读取application-test.yml配置
解决Spring Boot 2.0.0.RC2 + JUnit 5读取测试配置文件的问题
针对你遇到的场景,我整理了几个关键步骤和注解配置,帮你搞定测试类读取application-test.yml的问题:
测试类必备注解组合
你需要给测试类加上这几个核心注解:
@SpringBootTest:启动Spring Boot的测试上下文,这是Spring Boot测试的基础注解,会自动加载应用配置和Bean。@ActiveProfiles("test"):明确激活test环境,这样Spring会自动加载src/test/resources/application-test.yml配置文件,而不是默认的生产环境配置。@EnableConfigurationProperties(YourPropertiesClass.class):如果你的ConfigurationProperties类没有添加@Component注解,就需要用这个注解手动启用它,让Spring把配置绑定到这个类上。如果已经加了@Component,这个注解可以省略。
完整测试类示例
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @SpringBootTest @ActiveProfiles("test") @EnableConfigurationProperties(MyAppProperties.class) // 替换成你的Properties类 public class ConfigPropertiesTest { @Autowired private MyAppProperties myAppProperties; @Test void verifyConfigLoading() { // 这里可以写断言验证配置是否正确加载 assert myAppProperties.getApiKey() != null; assert myAppProperties.getMaxRetryCount() == 3; } }
额外注意事项
- 配置文件路径检查:确保
application-test.yml确实放在src/test/resources目录下,文件名拼写完全正确(大小写敏感,比如Application-Test.yml是不对的)。 - 依赖兼容性:Spring Boot 2.0.0.RC2对应的JUnit 5版本是
junit-jupiter-api:5.0.0-RC2,junit-platform-surefire-provider建议搭配1.0.0-RC2版本,避免版本不兼容导致的问题。 - Configuration类扫描:如果你的自定义
Configuration类不在主应用类的同包或子包下,需要在测试类或主配置类上添加@ComponentScan(basePackages = "com.your.config.package")来指定扫描路径,确保Spring能找到它。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

