Patrick Bray
Patrick Bray

Reputation: 640

How to exclude auto-configuration from Spring Boot WebMvcTest

I am trying to implement a Spring Boot Mock MVC unit test and would like to exclude the spring-cloud-consul auto configuration to avoid requiring connectivity to a remote service.

It looks like I should be able to achieve this with the below:

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

However this still appears to be trying to connect to remote Consul as I am unable to run this unit test when offline.

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)

If I add the -Ddebug to the unit test run configuration I am not seeing this listed in the exclusions:

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

I am wondering if this is because this config is loaded at bootstrap time?

Any help would be greatly appreciated, thanks in advance.

Upvotes: 1

Views: 2984

Answers (1)

Patrick Bray
Patrick Bray

Reputation: 640

Managed to find a work around by adding the following annotation to the test.

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

Upvotes: 2

Related Questions