小编典典

用于集成测试的Spring-boot默认配置文件

spring-boot

Spring-boot利用Spring配置文件(http://docs.spring.io/spring-
boot/docs/current/reference/html/boot-features-
profiles.html)允许例如为不同环境使用单独的配置。我使用此功能的一种方法是配置要由集成测试使用的测试数据库。但是,我想知道是否有必要创建自己的配置文件“测试”并在每个测试文件中显式激活此配置文件吗?现在,我通过以下方式进行操作:

  1. 在src / main / resources中创建application-test.properties
  2. 将测试特定的配置写在那里(现在只是数据库名称)
  3. 在每个测试文件中包括:
    @ActiveProfiles("test")
    

有没有更聪明/更简洁的方法?例如默认的测试配置文件?

编辑1:此问题与Spring-Boot 1.4.1有关


阅读 263

收藏
2020-05-30

共1个答案

小编典典

据我所知,没有什么可以直接解决您的请求-但我可以提出一项建议,可以帮助您:

您可以使用自己的测试注释,该注释是包含@SpringBootTest和的元注释@ActiveProfiles("test")。因此,您仍然需要专用的配置文件,但要避免在所有测试中分散配置文件定义。

该注释将默认为配置文件test,您可以使用元注释覆盖配置文件。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SpringBootTest
@ActiveProfiles
public @interface MyApplicationTest {
  @AliasFor(annotation = ActiveProfiles.class, attribute = "profiles") String[] activeProfiles() default {"test"};
}
2020-05-30