Spring Boot在测试中覆盖应用程序属性。

huangapple go评论131阅读模式
英文:

Spring boot override application properties in test

问题

如果我有一个名为 appplication.properties 的文件,内容如下:

url=someUrl
user=userOne
password=ABCD

但是如果我想在测试时将密码设置为其他值,比如:

password=someTest

我该如何做呢?

我需要在一个测试方法中完成以下操作:

@Test
void checkSomething{
    // 在调用 someMethod 之前仅针对此测试修改/覆盖密码
    someMethod();
}
英文:

If I have a appplication.properties like:

url=someUrl
user=userOne
password=ABCD

But if I want to be able to set the password when testing to something else, lets say:

password=someTest

How do I do that?

I need to do this in one test

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

答案1

得分: 1

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

在运行应用程序时,您可以使用以下命令来指定使用的配置文件:
-Dspring.active.profiles=testing

英文:

You can create a testing profile file something like application-testing.properties and specify the overridden properties there.

Now while running the application you can specify use profile using
-Dspring.active.profiles=testing

答案2

得分: 1

在src/test/resources目录下创建另一个application.properties文件,这是您所需的全部内容。
如果您想在一个方法中获取属性而不涉及Spring,可以这样做:

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

create another application.properties under src/test/resources thats all you need,
if you want to get properties to use in one method you can do i without involving spring :

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

答案3

得分: 1

有多种方法。

第一种方法:Spring配置文件

aplication.yaml:

spring.profiles.active=dev
---
spring.profile=dev
url=某个网址
user=用户一
password=ABCD
---
spring.profile=test
password=一些测试密码

测试类:

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

第二种方法:SpringBootTest属性

@RunWith(SpringRunner.class)
@SpringBootTest(properties = { "password=一些测试密码" })
public class MyTestClass {...}
英文:

There are multiple ways.

1st way: Spring Profile

aplication.yaml:

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

Test class:

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

2nd way: SpringBootTest Properties

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

huangapple
  • 本文由 发表于 2020年7月23日 18:28:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63052133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定