Я хочу протестировать класс, который просто отключает приложение:
@Component
public class ShutdownManager {
@Autowired
private ApplicationContext applicationcontext;
public int shutdown(int returnCode) {
return SpringApplication.exit(applicationcontext, () -> returnCode);
}
}
Тестовый пример, который я создал, таков:
public class ShutdownManagerTest {
@Test
public void should_shutdown_gracefully() {
SpringApplication app = new SpringApplication(TestClass.class);
ConfigurableApplicationContext context = app.run();
ShutdownManager shutdownManager = (ShutdownManager)context.getBean("shutdownManager");
int result = shutdownManager.shutdown(10);
assertThat(result).isEqualTo(10);
}
@SpringBootApplication
@ImportResource("classpath:/core/shutdownmanagertest.xml")
private static class TestClass {
public TestClass() {
}
public static void main(String[] args) {
}
}
}
Мой shutdownmanagertest.xml содержит только один компонент:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id = "shutdownManager" class = "com.mycodebase.ShutdownManager" />
</beans>
Однако, когда я запускаю это, он жалуется, что:
Field myOtherService in com.mycodebase.MyTask required a bean of type 'com.mycodebase.MyOtherService ' that could not be found.
Класс MyTask находится в том же пакете ShutdownManager, который содержит поле myOtherService с аннотацией @Autowire. Но он не определен в моем тестовом xml, который содержит только один компонент.
Может ли кто-нибудь помочь мне понять, почему он пытается разрешить bean-компонент, который не находится в контексте?




Это происходит потому, что так работает @SpringBootApplication.
This is a convenience annotation that is equivalent to declaring @Configuration, @EnableAutoConfiguration and @ComponentScan.
If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.
Таким образом, все в том же или подпакете ShutdownManagerTest подхватывается.
вам нужно добавить больше кода, чтобы решить эту проблему