Search code examples
spring-bootspring-testspring-cloud-config

How to exclude bootstrapping in META-INF/spring.factories from java tests


Had this line in resources/META-INF/spring.factories: org.springframework.cloud.bootstrap.BootstrapConfiguration=org.path.to.AWSConfig

Integration test executions using @RunWith(SpringRunner.class) were failing while running AWSConfig. The tests don't need AWSConfig to run. Tried many methods on SO of excluding AWSConfig, including:

  • @TestPropertySource(properties={"spring.autoconfigure.exclude=org.path.to.AWSConfig"})
  • @EnableAutoConfiguration(exclude = { AWSConfig.class})
  • Setting spring.cloud.config.enabled=false

But AWSConfig was still running (and failing). How do I exclude the bootstrapped configuration class from tests?

Test setup:

@RunWith(SpringRunner.class)
@WebMvcTest(UnitLeaderRequestController.class)
@WithMockUser
public class UnitLeaderRequestControllerTest {
    @Autowired
    MockMvc mvc;
    ...
}

Solution

  • QUICK SOLUTION:

    Adding this annotation to the Test Class excluded the bootstrapping:

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

    ALTERNATE SOLUTION:

    Based on How to disable Eureka and Spring Cloud Config in a WebMvcTest?

    I changed the annotation to @TestPropertySource(locations = "classpath:application-controller-tests.properties")

    , created application-controller-tests.properties in /resources and added spring.cloud.bootstrap.enabled = false to the file so multiple test classes could use the exclusion from 1 place.

    FURTHER THOUGHTS

    It's possible a better fix might have been to stop using META-INF/spring.factories at all, and use bootstrap-{env}.yml files. I was unsure of the implications of removing META-INF/spring.factories from the project.