How to load springboot custom test configuration for particular tests

Viewed 415

I have two spring junit tests that require different configurations. These are as follows

package some.pkg.name;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {Test1.ContextConfig.class})
public class Test1 {

    @Test
    public void test1() {
        // do something
    }

    @Configuration
    @ComponentScan("some.pkg.name")
    public static class ContextConfig {
        // bean definitions here
    }
}


package some.pkg.name;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {Test2.ContextConfig.class})
public class Test2 {

    @Test
    public void test2() {
        // do something
    }

    @Configuration
    public static class ContextConfig {
        // bean definitions here
    }
}

When I run Test1 I end up with Test1's beans AND Test2's beans. I've been at it for a while but can't figure it out. What am I doing wrong? I've tried putting the config classes in their own package but it hasn't worked. In Test1 I need spring's component scan, in Test2 the beans are created "by hand". The default component scan for the project is some.pkg.

Any ideas?

2 Answers

If you need spring main application component scan beans then don't specify the custom configuration on that test class

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {

    @Test
    public void test1() {
       // do something
    }

}


@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {Test2.ContextConfig.class})
public class Test2 {

    @Test
    public void test2() {
       // do something
    }

    @Configuration
    public static class ContextConfig {
      // bean definitions here
    }
}

The problem was solved by putting the configuration classes outside of the component scan, like so:

package some.pkg.name;

import some.config.ContextConfigTest1;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = ContextConfigTest1.class)
public class Test1 {

    @Test
    public void test1() {
        // do something
    }

}


package some.pkg.name;

import some.config.ContextConfigTest2;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = ContextConfigTest2.class)
public class Test2 {

    @Test
    public void test2() {
        // do something
    }
}


package some.config;

@Configuration
public class ContextConfigTest2 {
    // bean definitions here
}

package some.config;

@Configuration
@ComponentScan("some.pkg.name")
public class ContextConfigTest1 {
    // bean definitions here
}
Related