如何在Junit测试中更改代码中的Spring属性文件变量?

时间:2018-10-30 15:42:35

标签: spring spring-boot junit

我有一个

thing=false 

在我的Spring Boot项目的属性文件中。在为项目运行Junit测试时,我想要

 thing=true

我该怎么做?

3 个答案:

答案 0 :(得分:0)

只需将application.properties文件添加到:

src -> test -> resources

并将属性设置为所需值。

答案 1 :(得分:0)

Spring提供对相同用法@TestPropertySource批注的支持,它是一个类级别的批注,用于配置要添加到环境的PropertySources集合中的属性文件的location()和内联的properties()。用于集成测试的ApplicationContext。

示例

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = AppConfig.class)
@TestPropertySource(locations="classpath:test.properties")
public class SampleApplicationTests {

}

在Junit类路径中存在的test.properties中,您可以覆盖要在application.properties下提到的变量

答案 2 :(得分:0)

您可以使用带有{em> properties 参数的TestPropertySource批注为单元测试设置特定的配置属性:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@TestPropertySource(properties = {
    "thing=true"
})
public class ThingTrueTests {

}

这提供了一种无需使用properties / yaml文件即可设置配置属性的方法。但是,这是一个类级别的注释,因此它将应用于该类中的所有测试。

如果您有一组依赖于 thing 的测试为false,则将它们放在一个单元测试类中,并将所有依赖于 thing 的测试为true。另一个单元测试课程。

注意:如果您正在编写常规代码,则TestPropertySource批注将如下所示:

@TestPropertySource(properties = [
    "thing=true"
])