应用程序事件

自 TODAY Framework 5.3.3 起,TestContext 框架提供了对记录在 ApplicationContext 中发布的 应用程序事件 的支持, 以便在测试中对这些事件进行断言。在单个测试执行期间发布的所有事件都可以通过 ApplicationEvents API 获得,该 API 允许你将事件作为 java.util.Stream 进行处理。

要在测试中使用 ApplicationEvents,请执行以下操作。

  • 确保你的测试类使用了 @RecordApplicationEvents 注解或元注解。

  • 确保已注册 ApplicationEventsTestExecutionListener。但请注意, ApplicationEventsTestExecutionListener 默认已注册,只有在通过 @TestExecutionListeners 进行自定义配置且不包含默认监听器时,才需要手动注册。

  • 使用 @Autowired 标注一个 ApplicationEvents 类型的字段,并在测试和生命周期方法(如 JUnit Jupiter 中的 @BeforeEach@AfterEach 方法)中使用该 ApplicationEvents 实例。

    • 当使用 InfraExtension for JUnit Jupiter 时, 你可以在测试或生命周期方法中声明一个 ApplicationEvents 类型的方法参数, 作为测试类中 @Autowired 字段的替代方案。

以下测试类使用 JUnit Jupiter 的 InfraExtensionAssertJ 来断言在调用 Infra 管理的组件中的方法时发布的应用程序事件的类型:

  • Java

@JUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {

  @Autowired
  OrderService orderService;

  @Autowired
  ApplicationEvents events; (2)

  @Test
  void submitOrder() {
    // 调用 OrderService 中发布事件的方法
    orderService.submitOrder(new Order(/* ... */));
    // 验证是否发布了一个 OrderSubmitted 事件
    long numEvents = events.stream(OrderSubmitted.class).count(); (3)
    assertThat(numEvents).isEqualTo(1);
  }
}
1 使用 @RecordApplicationEvents 标注测试类。
2 为当前测试注入 ApplicationEvents 实例。
3 使用 ApplicationEvents API 计算发布的 OrderSubmitted 事件的数量。

有关 ApplicationEvents API 的更多详细信息,请参阅 ApplicationEvents javadoc