繁体   English   中英

Spring 引导覆盖测试中的应用程序属性

[英]Spring boot override application properties in test

如果我有一个appplication.properties ,例如:

url=someUrl
user=userOne
password=ABCD

但是,如果我希望能够在测试其他内容时设置密码,可以说:

password=someTest

我怎么做?

我需要在一次测试中做到这一点

@Test
void checkSomething{
    //change/override password before calling someMethod only for this test
    someMethod();
}

您可以创建一个类似于application-testing.properties的测试配置文件并在其中指定覆盖的属性。

现在,在运行应用程序时,您可以使用指定使用配置文件
-Dspring.active.profiles=testing

在 src/test/resources 下创建另一个 application.properties,这就是您所需要的,如果您想在一种方法中使用属性,您可以在不涉及 spring 的情况下进行操作:

InputStream input = Main.class.getResourceAsStream(yourproperties-path);
Properties prop = System.getProperties();
prop.load(input);

有多种方法。

第一种方式: Spring 配置文件

应用程序.yaml:

spring.profiles.active=dev
---
spring.profile=dev
url=someUrl
user=userOne
password=ABCD
---
spring.profile=test
password=someTest

测试 class:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class MyTestClass {...

第二种方式: SpringBootTest 属性

@RunWith(SpringRunner.class)
@SpringBootTest(properties = { "password=someTest" })
public class MyTestClass {...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM