问题描述
我有一个Spring-Boot应用程序,默认属性在类路径(src / main / resources / application.properties)中的 application.properties
文件中设置。
I have a Spring-Boot application where the default properties are set in an application.properties
file in the classpath (src/main/resources/application.properties).
我想在我的JUnit测试中使用在 test.properties
文件中声明的属性覆盖一些默认设置( src / test / resources / test.properties)
I would like to override some default settings in my JUnit test with properties declared in a test.properties
file (src/test/resources/test.properties)
我通常会为我的Junit测试提供专用的配置类,例如
I usualy have a dedicated Config Class for my Junit Tests, e.g.
package foo.bar.test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {
}
我首先想到的是使用 @PropertySource(classpath:test.properties)
在TestConfig类中可以解决这个问题,但这些属性不会覆盖application.properties设置(参见Spring-Boot Reference Doc - 。
I first thought that using @PropertySource("classpath:test.properties")
in the TestConfig class would do the trick, but these properties will not overwrite the application.properties settings (see Spring-Boot Reference Doc - 23. Externalized Configuration).
然后我试着在调用测试时使用 -Dspring.config.location = classpath:test.properties
。这很成功 - 但我不想为每次测试执行设置此系统属性。因此我把它放在代码中
Then I tried to use -Dspring.config.location=classpath:test.properties
when invoking the test. That was successful - but I don't want to set this system property for each test execution. Thus I put it in the code
@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {
static {
System.setProperty("spring.config.location", "classpath:test.properties");
}
}
不幸的是再次没有成功。
which unfortunatly was again not successful.
必须有一个关于如何使用<$ c $覆盖JUnit测试中的 application.properties
设置的简单解决方案c> test.properties 我一定忽略了。
There must be a simple solution on how to override application.properties
settings in JUnit tests with test.properties
that I must have overlooked.
推荐答案
你可以用 @TestPropertySource
覆盖 application.properties
中的值。来自其javadoc:
You can use @TestPropertySource
to override values in application.properties
. From its javadoc:
例如:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ExampleApplication.class)
@TestPropertySource(locations="classpath:test.properties")
public class ExampleApplicationTests {
}
这篇关于覆盖Junit Test中的默认Spring-Boot application.properties设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!