【问题标题】:Spring Consul - disable for unit testsSpring Consul - 禁用单元测试
【发布时间】:2017-01-30 01:07:39
【问题描述】:

更新

下面列出的我的课程 (ServiceDiscoveryConfiguration) 从未被使用过。即使我删除 @EnableDiscoveryClient 以尝试完全避免设置,它仍会尝试连接到 Consul。

唯一对我有用的是完全删除 Consul Maven 依赖:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-consul-all</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

如果不通过配置文件和注释设置,我该怎么做才能阻止 Consul 运行单元测试?

原创

我有一个使用 Spring Consul 的应用程序。 我设置了一个类来启用这样的发现:

@Profile ("!" + Profiles.UNIT_TEST)
@Configuration
@EnableDiscoveryClient
public class ServiceDiscoveryConfiguration {
}

如果我没记错的话,这应该禁用 Consul 部分。基本测试类(它是我所有单元测试之间共享的abstract)使用以下注释进行设置。这就是我认为问题所在。

@SpringBootTest (classes = Service.class)
@WebAppConfiguration
@TestExecutionListeners (...)
@DirtiesContext
@ActiveProfiles (Profiles.UNIT_TEST)
@Test (...)
public abstract class AbstractBootTest extends AbstractTestNGSpringContextTests {
  // ...
}

当我执行测试时,我得到:

引起:com.ecwid.consul.transport.TransportException: java.net.ConnectException:连接被拒绝

这让我相信配置文件激活不起作用,或者我在 @Profile 规范上使用 ! 运算符的语法没有按照我认为的那样做。根执行类本身具有基本注释,包括我知道的 @ComponentScan 注释,其中包含正在扫描的相应包。

协助?

【问题讨论】:

    标签: spring spring-boot consul service-discovery


    【解决方案1】:

    您可以通过以下方式禁用

    @TestPropertySource(properties = {"spring.cloud.consul.config.enabled=false"})
    

    【讨论】:

      【解决方案2】:

      如果你的项目中有bootstrap.properties文件,你应该在test/resources下创建bootstrap.properties文件:

      spring.application.name=<service-name>
      spring.cloud.bus.enabled=false
      spring.cloud.discovery.enabled=false
      spring.cloud.consul.enabled=false
      spring.cloud.consul.config.enabled=false
      

      这将禁用测试中的领事集成

      【讨论】:

      • 啊!这是一个更好的主意!
      【解决方案3】:

      在 test/resources 下的 application.properties 文件中添加以下属性

      spring.cloud.discovery.enabled=false
      spring.cloud.consul.enabled=false
      spring.cloud.consul.config.enabled=false
      

      这将在测试您的应用程序时禁用 consul 集成

      【讨论】:

        【解决方案4】:

        问题是,如果你在类路径中有 spring-consul,它会尝试自动配置它

        【讨论】:

        • 对此的任何解决方案
        【解决方案5】:

        配置文件注释正确

        @Profile ("!" + Profiles.UNIT_TEST) 
        

        配置文件激活看起来还可以

        @ActiveProfiles (Profiles.UNIT_TEST)
        

        你写的是你正在使用 ComponentScan,这很重要,因为如果 bean 是由 @Bean 注释方法实例化的,那么 bean 上的 @Profile 注释将被忽略。可能你再检查一下,看看,这不会发生吗?

        要缩小问题范围,您可以尝试:

        在ServiceDiscoveryConfiguration的构造函数中设置断点,查看是否实例化

        删除@EnableDiscoveryClient 看看这是否真的是您的问题的原因

        【讨论】:

        • 我认为这与个人资料无关。我正在更新我的问题,因为我必须删除 Maven 依赖项。
        • 所以在调试之后,这个类根本就不会被击中。就好像它忽略了那个特定的配置选项。
        猜你喜欢
        • 2016-06-12
        • 2014-02-24
        • 1970-01-01
        • 2015-09-19
        • 2019-03-30
        • 1970-01-01
        • 2021-06-07
        • 1970-01-01
        • 2018-08-06
        相关资源
        最近更新 更多