JUnit SpringBootTest postconstruct 和 shutdown
JUnit SpringBootTest postconstruct and shutdown
我正在尝试测试一个 SpringBoot 应用程序,它使用 ServiceRegistry
(例如 Eureka/Consul)自注册,然后在关闭时注销。该实现只是扩展了预先存在的 spring 云抽象,例如
@Component
public class MyAutoRegistration extends AbstractAutoServiceRegistration<MyRegistration> {
@override
protected void register(){...}
@Override
protected void deregister(){...}
注册和注销在示例应用程序中按预期工作,但我无法在 SpringBootTest 中捕获它,因为测试在自注册发生之前运行(即在 spring 上下文加载和日志显示 "app started in N seconds...")。同样,测试在应用程序关闭之前完成(即在 spring 上下文关闭之前),因此在注销启动之前完成。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyClientAutoConfiguration.class)
@EnableAutoConfiguration
public class MyRegistrationTest {
@Autowired
MyRegistration record;
@SpyBean
@Autowired
ServiceRegistry<MyRegistration> registry;
@Test
public void registers_and_deregisters(){
verify(registry, times(1)).register(record);
verify(registry, times(1)).deregister(record);
}
Found a test class 做了类似的事情,但有点超出我的理解范围。有没有一种直接的方法可以将 auto registration/deregistration 包含到 @SpringBootTest 中?
Red-herring...我的实际问题是我的类路径中没有 spring-boot-starter-web
,它隐式导入 spring-boot-starter-tomcat
。没有这些,我试图测试的自动注册组件将无法自动配置。将 starter-web
放回类路径解决了我的问题。
我正在尝试测试一个 SpringBoot 应用程序,它使用 ServiceRegistry
(例如 Eureka/Consul)自注册,然后在关闭时注销。该实现只是扩展了预先存在的 spring 云抽象,例如
@Component
public class MyAutoRegistration extends AbstractAutoServiceRegistration<MyRegistration> {
@override
protected void register(){...}
@Override
protected void deregister(){...}
注册和注销在示例应用程序中按预期工作,但我无法在 SpringBootTest 中捕获它,因为测试在自注册发生之前运行(即在 spring 上下文加载和日志显示 "app started in N seconds...")。同样,测试在应用程序关闭之前完成(即在 spring 上下文关闭之前),因此在注销启动之前完成。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyClientAutoConfiguration.class)
@EnableAutoConfiguration
public class MyRegistrationTest {
@Autowired
MyRegistration record;
@SpyBean
@Autowired
ServiceRegistry<MyRegistration> registry;
@Test
public void registers_and_deregisters(){
verify(registry, times(1)).register(record);
verify(registry, times(1)).deregister(record);
}
Found a test class 做了类似的事情,但有点超出我的理解范围。有没有一种直接的方法可以将 auto registration/deregistration 包含到 @SpringBootTest 中?
Red-herring...我的实际问题是我的类路径中没有 spring-boot-starter-web
,它隐式导入 spring-boot-starter-tomcat
。没有这些,我试图测试的自动注册组件将无法自动配置。将 starter-web
放回类路径解决了我的问题。