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

Spring-boot, JUnit tests using different profiles

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

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

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

@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 配置文件?实现我想要做的事情的最佳实践是什么?

您是否尝试过使用

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

还要确保应用程序-tensorflow.properties 在 /src/test/resources

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

此外,您需要配置加载配置文件。有两个选项:

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

示例测试class:

@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