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

问题描述 投票:1回答:2

我正在尝试使用app.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测试中是否有特殊的方法来指定弹簧轮廓?实现我想要做的事情的最佳做法是什么?

java spring spring-boot junit integration-testing
2个回答
3
投票

第一步:将@ActiveProfiles添加到测试类以定义活动配置文件。

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

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

示例测试类:

@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


1
投票

你试过用你的测试注释吗?

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(profiles = {"tensorflow"})

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

© www.soinside.com 2019 - 2024. All rights reserved.