测试里报 Unable to find a @SpringBootConfiguration 是怎么回事?测试类放在哪个包才找得到?补救办法各有什么副作用?这篇在 Spring Boot 4.0.8 上把包的位置逐个试了一遍。
测试类在 demo.app(和主类同一个包):通过:上下文加载成功,Bean 定义数 52;Greeter Bean:1 个 测试类在 demo.app.sub(主类包的子包):通过:上下文加载成功,Bean 定义数 52;Greeter Bean:1 个 测试类在 demo.test(主类包的兄弟包):失败:Unable to find a @SpringBootConfiguration by searching packages upwards from the test. You can use @ContextConfiguration, @SpringBootTest(classes=...) or other Spring Test supported mechanisms to explicitly declare the configuration classes to load. Classes annotated with @TestConfiguration are not considered. 测试类在 demo(主类包的父包):失败:Unable to find a @SpringBootConfiguration by searching packages upwards from the test. You can use @ContextConfiguration, @SpringBootTest(classes=...) or other Spring Test supported mechanisms to explicitly declare the configuration classes to load. Classes annotated with @TestConfiguration are not considered. 测试类在 other.pkg(完全不相关的包):失败:Unable to find a @SpringBootConfiguration by searching packages upwards from the test. You can use @ContextConfiguration, @SpringBootTest(classes=...) or other Spring Test supported mechanisms to explicitly declare the configuration classes to load. Classes annotated with @TestConfiguration are not considered.
同包与子包能找到,兄弟包、父包、无关包找不到。
@SpringBootTest(classes = App.class):通过:上下文加载成功,Bean 定义数 52;Greeter Bean:1 个 @SpringBootTest + @ContextConfiguration(classes = App.class):通过:上下文加载成功,Bean 定义数 52;Greeter Bean:1 个 测试类里有一个嵌套的 @Configuration 类:通过:上下文加载成功,Bean 定义数 8;Greeter Bean:0 个 测试类里有一个嵌套的 @TestConfiguration 类:失败:Unable to find a @SpringBootConfiguration by searching packages upwards from the test. You can use @ContextConfiguration, @SpringBootTest(classes=...) or other Spring Test supported mechanisms to explicitly declare the configuration classes to load. Classes annotated with @TestConfiguration are not considered.
classes = App.class 或 @ContextConfiguration;嵌套 @Configuration 只得到一个几乎空的上下文。
demo.app2 里有 App2 和 App3 两个主类,测试类在 demo.app2:失败:Found multiple @SpringBootConfiguration annotated classes [Generic bean: class=demo.app2.App2; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; fallback=false; factoryBeanName=null; factoryMethodName=null; initMethodNames=null; destroyMethodNames=null; defined in fi
同一个包里有两个主类时报 Found multiple,要用 classes 指定。