1

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

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

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

但是,这似乎仍在尝试连接到远程领事,因为我无法在离线时运行此单元测试。

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

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

任何帮助将不胜感激,在此先感谢。

4

1 回答 1

1

通过在测试中添加以下注释来设法找到解决方法。

@TestPropertySource(properties="spring.cloud.consul.enabled=false")
于 2017-12-06T19:23:42.530 回答