Java Spring在测试期间从包私有类获取配置
我从Spring2.0更新到SpringBoot2.1,服务测试失败 我的测试结构:Java Spring在测试期间从包私有类获取配置,java,spring,spring-boot,junit,spring-test,Java,Spring,Spring Boot,Junit,Spring Test,我从Spring2.0更新到SpringBoot2.1,服务测试失败 我的测试结构: com ... service ServiceTest.java web ControllerTest.java ServiceTest.java: @ExtendWith(SpringExtension.class) @DataJpaTest public class ServiceTest { @Autowired private OtherS
com
...
service
ServiceTest.java
web
ControllerTest.java
ServiceTest.java:
@ExtendWith(SpringExtension.class)
@DataJpaTest
public class ServiceTest {
@Autowired
private OtherService otherService;
...
}
@ExtendWith(SpringExtension.class)
@WebMvcTest(secure = false)
@Import(WebMvcConfig.class)
@SuppressWarnings("Duplicates")
public class GroupControllerTest {
@Configuration
static class Config {
@Bean
public Controller controller() {
return new Controller();
}
}
}
ControllerTest.java:
@ExtendWith(SpringExtension.class)
@DataJpaTest
public class ServiceTest {
@Autowired
private OtherService otherService;
...
}
@ExtendWith(SpringExtension.class)
@WebMvcTest(secure = false)
@Import(WebMvcConfig.class)
@SuppressWarnings("Duplicates")
public class GroupControllerTest {
@Configuration
static class Config {
@Bean
public Controller controller() {
return new Controller();
}
}
}
在ServiceTest期间,我收到错误:
原因:
org.springframework.beans.factory.support.bean定义覆盖异常:
类路径中定义了名为“controller”的无效bean定义
资源[com/../web/ControllerTest$Config.class]
spring如何从GroupControllerTest的内部包私有类获取ServiceTest的配置?
真奇怪!为什么要扫描同级目录中的配置?这是Spring TestContext框架中的预期行为。如果没有明确指定要使用的
@Configuration
类,Spring将在当前测试类中查找静态嵌套类
以下是《弹簧参考手册》的摘录
如果省略@ContextConfiguration
注释中的classes属性,TestContext框架将尝试检测默认配置类的存在。具体而言,AnnotationConfigContextLoader
和AnnotationConfigWebContextLoader
检测满足配置类实现要求的测试类的所有静态嵌套类,如@configuration
javadoc中所述。请注意,配置类的名称是任意的。此外,如果需要,测试类可以包含多个静态嵌套配置类
由于您使用的是Spring Boot,您应该使用
@SpringBootTest
注释您的测试类,以便Spring Boot找到您的@Configuration
类。我理解这一点,但Spring从其他类的静态内部类获取配置,非当前?核心Spring中的Spring TestContext框架不会扫描除当前测试类之外的任何类中的静态嵌套类。因此,必须有其他东西通过组件扫描拉入该类。可能是您的@Configuration
类或Spring Boot。如果您使用@SpringBootTest
注释ServiceTest
,会发生什么?非常感谢您正确地进行了组件扫描。我有@SpringBootApplication和@ComponentScan(…),它们扫描我的所有包,但我没有意识到它也会影响测试包。所以我需要重构)