java - Spring-boot,JUnit 测试使用不同的配置文件

标签 java spring spring-boot junit integration-testing

我正在尝试使用 application.properties 配置文件使用 JUnit 进行集成测试,以检查两个不同的平台。

我尝试使用基本配置文件 application.properties 执行此操作,其中包含两个平台的通用配置,最重要的是我添加了属性文件 application-tensorflow.properties application-caffe.properties 每个平台都有特定的平台配置,但我发现它在 JUnit 中的工作方式与我在主应用程序中使用的方法不同。

我的测试配置类如下所示:

@Configuration
@PropertySource("classpath:application.properties")
@CompileStatic
@EnableConfigurationProperties
class TestConfig {...}

我正在使用 @PropertySource("classpath:application.properties") 所以它会识别我的基本配置,我也写了 spring.profiles.active=tensorflow,希望它能识别 tensorflow 应用程序配置文件,但它不会从文件中读取:/src/test/resources/application-tensorflow.properties,也不会从 /src/main/resources/application-tensorflow.properties 就像在主应用程序中一样。

在 JUnit 测试中是否有特殊的方法来指定 spring profile?实现我想要做的事情的最佳实践是什么?

最佳答案

首先:将 @ActiveProfiles 添加到您的测试类以定义 Activity 配置文件。

此外,您需要配置应该加载的配置文件。有两种选择:

  • 在使用 @ContextConfiguration(classes = TheConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
  • 的简单集成测试中
  • 在完整的 Spring Boot 测试中使用 @SpringBootTest

示例测试类:

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

    @Autowired
    private Environment env;

    @Test
    public void readProps() {
        String value = env.getProperty("prop1") + " " + env.getProperty("prop2");
        assertEquals("Hello World", value);
    }
}

现在评估文件 src/test/resources/application.propertiessrc/test/resources/application-test.properties

关于java - Spring-boot,JUnit 测试使用不同的配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353127/

相关文章:

java - 使用 Apache Spark 将 RDD 写入文本文件

java - 在 gradle 上的 war 任务之前替换文件中的字符串 ${stringKey}

java - 无法将 XMLSlurper 添加到 Eclipse Groovy 项目

java - 如何在基于 war 的应用程序中加载多个 jar 文件的 spring bean

eclipse - 从 pom.xml 设置事件 Spring 配置文件并与 IDE 集成

java - 如何在 JBoss 上部署 JAR 文件?

java - 无法使用enableconfigurationproperties读取属性

java - Spring-Data-Jpa 中一对多映射的 JSON 结果错误

java - @Scheduled 方法中的 Spring @Async 方法调用

java - 为什么可以将 JFrame 强制转换为 JPanel?