Spring Boot测试 - 覆盖bootstrap.properties

时间:2017-02-01 16:52:02

标签: spring spring-boot

我们在Spring Boot应用程序中使用bootstrap.properties来配置与Spring Cloud Config相关的属性。

我们希望在测试期间忽略这些属性,因为我们不想连接到配置服务器进行单元测试。因此,我们正在寻找一种方法来完全撤消主bootstrap.properties的属性,并为测试或覆盖选择性属性提供新的属性。

我们尝试使用src/test/resources/bootstrap.properties属性创建src/test/resources/bootstrap-test.propertiesspring.cloud.config.enabled=false,但它没有用。

我们尝试在启动TestClass之前设置如下

static {
    System.setProperty("spring.cloud.config.enabled", "false");
}

它没有用。

虽然Spring Boot文档非常适合application.properties如何工作,但我找不到bootstrap.properties的一个引用。

我们非常感谢您在测试过程中以可靠的方式覆盖bootstrap.properties

3 个答案:

答案 0 :(得分:18)

如果您使用@SpringBootTest注释,则可以使用以下内容覆盖bootstrap.properties中的属性:

@SpringBootTest(properties = "spring.cloud.config.enabled=false")

否则,你可以:

  1. @ActiveProfiles('test')添加到测试类
  2. 创建名为bootstrap-test.properties
  3. 的文件
  4. 添加要覆盖的属性,例如spring.cloud.config.enabled=false
  5. 更新:如果要为所有测试禁用spring cloud配置,只需在bootstrap.properties文件夹中创建一个test/resources即可以下属性:

    spring.cloud.config.enabled=false

答案 1 :(得分:8)

(在这里回答我自己的问题)

经过大量尝试和错误后发现,通过将弹簧配置文件设置为test,它实际上会选择bootstrap-test.properties并将其与主bootstrap.properties文件合并。

在这种情况下,设置spring.cloud.config.enabled=false仍在尝试引导,因为它在主引导程序中设置为spring.cloud.config.server.bootstrap = true,因此我们必须在bootstrap-test.properties中将此属性设置为false以使其处于非活动状态服务器完全。

希望这有助于某人。

答案 2 :(得分:0)

对于手动测试,我将本地application.yml和bootstrap.yml文件添加到了工作目录的根目录。 application.yml仅包含一行:

spring.cloud.bootstrap.location: file:.

此设置将激活工作目录中的本地bootstrap.yml文件,并禁用类路径中的文件。这个想法来自Spring Boot 2 #466

相关问题