如何解决无法从单元测试中将属性加载到 spring 环境中
目标详情
我正在使用 Spring Boot 2.4.4 为应用程序配置 Junit 测试。我想设置一个 spring boot 单元测试配置来实现以下目标:
- 使用一个名为 AppConfig 的 @Configuration bean 作为主应用程序代码(驻留在 src/main 中)和一个不同的 @Configuration bean 称为 TestConfig 用于 junit 测试代码(驻留在 src/test 中)
- 使用位于 src/main/resources 下的主应用程序代码 (application.main.properties) 的属性文件。
- 使用另一个包含环境特定的测试设置的属性文件 (application.test.properties)。该文件将位于 src/test/resources 下。
目的是避免重复任何已经在 src/main 目录下定义的 .properties 文件和类文件。
预期与实际结果
我需要的是在主应用程序代码或 junit 测试运行时将属性注入到 Spring 环境中。 我遇到的问题是,当我运行 junit 测试时,没有任何属性被加载到 spring 环境中。然而,当主代码运行时,它们会正确加载。
AppConfig 类在 src/main
@Configuration
@PropertySource("classpath:application.main.properties")
@ComponentScan(basePackages = ..... )
public class AppConfig {
....
}
TestConfig 类在 src/test
@Profile("test")
@Configuration
@PropertySource("classpath:application.main.properties")
@TestPropertySource(locations={"classpath:application.test.properties"})
@ComponentScan(basePackages = ..... )
public class TestConfig {
....
}
位于 src/test 下的单元测试类使用 TestConfig 作为它的 @ContextConfiguration
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class AUnitTest {
// my.property1 and my.property2 should be loaded from application.main.properties
// my.property3 should be loaded from application.test.properties
// However it does not work :(
}
application.main.properties 文件位于 src/main/resources
my.property1=value_for_property1
my.property2=value_for_property2
application.test.properties 文件位于 src/test/resources
my.property3=value_for_property3
总结一下,当主应用程序代码使用 AppConfig 配置运行时,属性会正确加载,但不会为使用 TestConfig 配置的单元测试加载。谁能看到我的 TestConfig 配置有什么问题?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。