应用事件
TestContext框架提供了对在ApplicationContext中发布的应用程序事件的记录支持,以便可以在测试中对这些事件进行断言检查。在单个测试执行过程中发布的所有事件都可以通过ApplicationEvents API获取,该API允许您将这些事件作为java.util.Stream来处理。
要在测试中使用ApplicationEvents,请按照以下步骤操作。
-
确保你的测试类被标注或元标注了@RecordApplicationEvents。
-
确保
ApplicationEventsTestExecutionListener已被注册。不过需要注意的是,ApplicationEventsTestExecutionListener是默认注册的,只有当你通过@TestExecutionListeners自定义了配置且不包含默认监听器时,才需要手动进行注册。 -
在使用JUnit Jupiter的Spring扩展时,在@Test、@BeforeEach或@AfterEach方法中声明一个类型为
ApplicationEvents的方法参数。- 由于
ApplicationEvents的作用域仅限于当前测试方法的生命周期,这是推荐的做法。
- 由于
-
或者,你也可以用@Autowired标注一个类型为
ApplicationEvents的字段,并在测试和生命周期方法中使用该ApplicationEvents实例。
ApplicationEvents 是作为 可解析依赖(resolvable dependency)注册到 ApplicationContext 中的,其作用范围仅限于当前测试方法的生命周期内。因此,在测试方法的生命周期之外无法访问 ApplicationEvents,也无法将其通过 @Autowired 注解注入到测试类的构造函数中。
以下测试类使用了SpringExtension(适用于JUnit Jupiter)和AssertJ,来断言在Spring管理的组件中调用方法时发布的应用事件的类型:
- Java
- Kotlin
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents 1
class OrderServiceTests {
@Test
void submitOrder(@Autowired OrderService service, ApplicationEvents events) { 2
// 调用OrderService中发布事件的方法
服务等.submitOrder(new Order(/* ... */));
// 验证是否发布了OrderSubmitted事件
long numEvents = events.stream(OrderSubmitted.class).count(); 3
.assertThat(numEvents).isEqualTo(1);
}
}
用
@RecordApplicationEvents注解测试类。为当前测试注入
ApplicationEvents实例。使用
ApplicationEventsAPI来统计发布了多少个OrderSubmitted事件。
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents 1
class OrderServiceTests {
@Test
fun submitOrder(@Autowired service: OrderService, events: ApplicationEvents) { 2
// 调用OrderService中发布事件的方法
服务等.submitOrder(Order(/* ... */))
// 验证是否发布了OrderSubmitted事件
val numEvents = events.stream(OrderSubmitted::class).count() 3
assertThat(numEvents).isEqualTo(1)
}
}
用
@RecordApplicationEvents注解测试类。为当前测试注入
ApplicationEvents实例。- \ [#3] 使用
ApplicationEventsAPI来统计发布了多少个OrderSubmitted事件。
有关ApplicationEvents API的更多详细信息,请参阅ApplicationEvents javadoc。