java—无法从单元测试将属性加载到spring环境中

j8yoct9x  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(181)

关于目标的详细信息
我使用springboot2.4.4为应用程序配置junit测试。我想设置一个spring boot单元测试配置,以实现以下目标:
对主应用程序代码(驻留在src/main中)使用一个名为appconfig的@configuration bean,对junit测试代码(驻留在src/test中)使用另一个名为testconfig的@configuration bean
使用src/main/resources下的主应用程序代码(application.main.properties)的属性文件。
使用另一个属性文件,该文件将包含测试的特定于环境的设置(application.test.properties)。此文件将位于src/test/resources下。
这样做的目的是避免复制已经在src/main目录下定义的任何.properties文件和类文件。
预期与实际结果
我需要的是在运行主应用程序代码或junit测试时将属性注入到spring环境中。我遇到的问题是,当我运行junit测试时,没有任何属性被加载到spring环境中。但是,当主代码运行时,它们被正确加载。
src/main中的appconfig类

@Configuration
@PropertySource("classpath:application.main.properties")
@ComponentScan(basePackages = ..... )
public class AppConfig {
    ....
}

src/test中的testconfig类

@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 :(
}

位于src/main/resources中的application.main.properties文件

my.property1=value_for_property1
my.property2=value_for_property2

位于src/test/resources中的application.test.properties文件

my.property3=value_for_property3

总而言之,当使用appconfig配置运行主应用程序代码时,属性是正确加载的,但是对于使用testconfig配置的单元测试,属性没有加载。有人能看到我的testconfig配置有什么问题吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题