我有一个Spring-Boot应用程序,其中在应用程序中设置了默认属性。属性文件在类路径(src/main/resources/application.properties)。

我想用测试中声明的属性覆盖JUnit测试中的一些默认设置。属性文件(src/test/resources/test. Properties)

我通常为我的Junit测试有一个专用的配置类,例如。

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 {

}

我最初认为在TestConfig类中使用@PropertySource("classpath:test.properties")可以达到目的,但是这些属性不会覆盖应用程序。属性设置(参见Spring-Boot参考文档- 23。外部化配置)。

然后我尝试使用-Dspring.config.location=classpath:test。属性。这是成功的——但是我不想为每次测试执行都设置这个系统属性。因此我把它放在代码中

@Configuration
@Import(CoreConfig.class)
@EnableAutoConfiguration
public class TestConfig {

  static {
    System.setProperty("spring.config.location", "classpath:test.properties");
  }

}

不幸的是,这次也没有成功。

必须有一个简单的解决方案如何覆盖应用程序。使用test在JUnit测试中设置属性。我一定是忽略了这些特性


当前回答

您也可以创建一个应用程序。在src/test/resources中的属性文件中,你的junit是在这里编写的。

其他回答

Spring Boot自动加载src/test/resources/application。属性,如果使用以下注释

@RunWith(SpringRunner.class)
@SpringBootTest

重命名test。应用程序的属性。属性来利用自动配置。

如果您只需要加载属性文件(到环境中),您也可以使用下面的方法,如下所述

@RunWith(SpringRunner.class)
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class) 

[更新:覆盖测试的某些属性]

添加src /主/资源/ application-test.properties。 用@ActiveProfiles(“test”)注释测试类。

这将加载应用程序。属性,然后应用程序测试。根据这里定义的规则,将属性放入测试用例的应用程序上下文中。

演示- https://github.com/mohnish82/so-spring-boot-testprops

使用

使用.yaml file-ending声明的属性 Spring-Boot 2.7 类路径中有多个.yaml文件

我注意到@TestPropertySource(位置)的优先级没有像使用.properties文件一样被应用。

我遇到的问题是,Spring一直在加载所有的.yaml属性(特别是那些来自产品的属性),并使用为prod指定的值覆盖用于测试的属性。

我们提出了通过指定我的应用程序测试来覆盖配置抓取机制的变通方法。Yaml作为唯一的属性使用如下:

@TestPropertySource(properties = "spring.config.location=classpath:/application-test.yaml")

否则,我们可以更改默认的属性配置器名称,设置属性spring.config.name=test,然后使用类路径资源 src /测试/测试。springapplication的本地实例将从这个分离的测试中自动配置。属性,忽略应用程序属性;

优点:自动配置测试;

缺点:在C.I.层暴露“spring.config.name”属性

裁判:http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

spring.config.name=application #配置文件名

另一种适用于覆盖测试中的一些属性的方法,如果你使用@SpringBootTest注释:

@SpringBootTest(properties = {"propA=valueA", "propB=valueB"})
I just configured min as the following :

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console


# changing the name of my data base for testing
spring.datasource.url= jdbc:h2:mem:mockedDB
spring.datasource.username=sa
spring.datasource.password=sa



# in testing i don`t need to know the port

#Feature that determines what happens when no accessors are found for a type
#(and there are no annotations to indicate it is meant to be serialized).
spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false`enter code here`