如何为特定测试加载 spring boot 自定义笑话配置

How to load springboot custom test configuration for particular tests

我有两个 spring 需要不同配置的 junit 测试。这些如下

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
    }
}

当我 运行 Test1 时,我得到了 Test1 的 bean 和 Test2 的 bean。我已经研究了一段时间,但无法弄清楚。我究竟做错了什么?我试过将配置 类 放在他们自己的包中,但没有用。在 Test1 中我需要 spring 的组件扫描,在 Test2 中创建了 bean "by hand"。项目的默认组件扫描是 some.pkg.

有什么想法吗?

如果您需要 spring 主应用程序组件扫描 bean,则不要在该测试中指定自定义配置 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
    }
}

问题已通过将配置 类 置于组件扫描之外解决,如下所示:

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
}