【问题标题】:Spring-boot, JUnit tests using different profilesSpring-boot,使用不同配置文件的 JUnit 测试
【发布时间】:2019-02-20 12:22:36
【问题描述】:

我正在尝试使用 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,希望它能识别张量流应用程序配置文件,但它不会从文件中读取:/src/test/resources/application-tensorflow.properties,也不像在主应用程序中那样来自/src/main/resources/application-tensorflow.properties

在 JUnit 测试中是否有特殊的方法来指定弹簧配置文件?实现我想要做的事情的最佳实践是什么?

【问题讨论】:

    标签: java spring spring-boot junit integration-testing


    【解决方案1】:

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

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

    • 在与@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

    【讨论】:

      【解决方案2】:

      您是否尝试过使用

      注释您的测试
      @RunWith(SpringRunner.class)
      @SpringBootTest
      @ActiveProfiles(profiles = {"tensorflow"})
      

      还要确保 application-tensorflow.properties 在 /src/test/resources 下

      【讨论】:

      • 是的,我不明白为什么在我指定了许多变体的配置文件后它不访问 tensorflow.application 文件。
      • 您是否使用 @SpringBootTest 和 @RunWith(SpringRunner.class) 注释了您的测试? application-tensorflow.properties 在 /src/test/resources 下吗?
      • 是的,就是这样。如果您愿意,请将此建议写为答案,我会将其标记为问题解决者。
      猜你喜欢
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2019-04-26
      • 2017-12-25
      • 2019-10-26
      相关资源
      最近更新 更多