簡體   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