mercredi 23 mai 2018

Excluding Configuration in Spring boot test

I have the following setup in a maven project. Configuration class for the productive code:

package com.example;
@Configuration
public class MyConfiguration {
    @Bean
    public A beanA() {
      return new A();
    }
    ...
}

Then I have one test, that has an internal Configuration:

package com.example;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MyConfiguration.class, SpringConfigurationTest.MyTestConfiguration.class})
public class SpringConfigurationTest {
    @TestConfiguration
    static class MyTestConfiguration {
        @Bean
        public A beanA() {
          return mock(A.class);
        }    
    }
}

The tests in this class work fine. Then I do have another Test class in sub package:

package com.example.sub;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {MyConfiguration.class, AnotherSpringConfigurationTest.MyTestConfiguration.class})
public class AnotherSpringConfigurationTest {
    @TestConfiguration
    static class MyTestConfiguration {
        @Bean
        public B beanB() {
          return new B()
        }    
    }
}

When running tests in this class the test configuration from SpringConfigurationTest.MyTestConfiguration is also included. My guess the reason for this is the inclusion of MyConfiguration which lies in the root directory. The effect is that in AnotherSpringConfigurationTest the bean A is mocked instead of a real instance.

How can I avoid that configuration classes inside other tests are 'leaked' into other tests?

I have seen Spring-boot default profile for integration tests which uses Spring profiles in Spring Boot 1.4.1, while I am using Spring Boot 2.0.1. Though I am sure it could be done.

Another approach I could think of would be to use component scanning to pick up the contexts and exclude all those that I do not want, but that is a bit cumbersome, as I would much prefer an approach where I define what I want to use instead of what should not be used.

Is there an easy and elegant solution with Spring Boot 2 to avoid conflicting context configurations?

Aucun commentaire:

Enregistrer un commentaire