如何从Spring Boot WebMvcTest中排除自动配置

时间:2017-12-06 19:04:31

标签: spring spring-mvc spring-boot spring-cloud-consul

我正在尝试实施Spring Boot Mock MVC单元测试,并希望排除spring-cloud-consul自动配置,以避免需要连接到远程服务。

看起来我应该能够通过以下方式实现这一目标:

@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class, excludeAutoConfiguration = ConsulAutoConfiguration.class)
@AutoConfigureMockMvc(addFilters = false, printOnlyOnFailure = false)

然而,这似乎仍然试图连接到远程Consul,因为我无法在离线时运行此单元测试。

Caused by: org.apache.http.conn.ConnectTimeoutException: Connect to consul.****:8500 [consul.****/**.**.**.**] failed: connect timed out
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:150)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)

如果我将-Ddebug添加到单元测试运行配置中,我没有在排除项中看到这个:

Positive matches:
-----------------

ConsulAutoConfiguration matched:
      - AllNestedConditions 2 matched 0 did not; NestedCondition on ConditionalOnConsulEnabled.OnConsulEnabledCondition.FoundClass @ConditionalOnClass found required class 'com.ecwid.consul.v1.ConsulClient'; @ConditionalOnMissingClass did not find unwanted class; NestedCondition on ConditionalOnConsulEnabled.OnConsulEnabledCondition.FoundProperty @ConditionalOnProperty (spring.cloud.consul.enabled) matched (ConditionalOnConsulEnabled.OnConsulEnabledCondition)

Exclusions:
-----------

    None

我想知道这是因为这个配置是在bootstrap时加载的?

非常感谢任何帮助,提前谢谢。

1 个答案:

答案 0 :(得分:0)

通过向测试添加以下注释来管理以找到解决方法。

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