我有两个要求不同配置的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。我已经有一段时间了,但无法弄清楚。我究竟做错了什么?我试过将config类放在自己的程序包中,但没有用。在Test1
中,我需要进行spring的组件扫描,在Test2
中,“手工”创建bean。该项目的默认组件扫描为some.pkg
。
有什么想法吗?
答案 0 :(得分:1)
如果您需要spring主要应用程序组件扫描bean,则不要在该测试类上指定自定义配置
npm i
答案 1 :(得分:0)
通过将配置类放置在组件扫描之外解决了该问题,如下所示:
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
}