应用程序事件
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 在 ApplicationContext 中注册为可解析依赖项,其作用域限定于当前测试方法的生命周期。因此,ApplicationEvents 不能在测试方法的生命周期之外访问,也不能通过 @Autowired 注入到测试类的构造函数中。 |
以下测试类使用 JUnit Jupiter 的 SpringExtension 和 AssertJ 来断言在调用 Spring 管理组件中的方法时发布的应用事件的类型
-
Java
-
Kotlin
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {
@Test
void submitOrder(@Autowired OrderService service, ApplicationEvents events) { (2)
// Invoke method in OrderService that publishes an event
service.submitOrder(new Order(/* ... */));
// Verify that an OrderSubmitted event was published
long numEvents = events.stream(OrderSubmitted.class).count(); (3)
assertThat(numEvents).isEqualTo(1);
}
}
| 1 | 使用 @RecordApplicationEvents 注解测试类。 |
| 2 | 注入当前测试的 ApplicationEvents 实例。 |
| 3 | 使用 ApplicationEvents API 计算发布了多少个 OrderSubmitted 事件。 |
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {
@Test
fun submitOrder(@Autowired service: OrderService, events: ApplicationEvents) { (2)
// Invoke method in OrderService that publishes an event
service.submitOrder(Order(/* ... */))
// Verify that an OrderSubmitted event was published
val numEvents = events.stream(OrderSubmitted::class).count() (3)
assertThat(numEvents).isEqualTo(1)
}
}
| 1 | 使用 @RecordApplicationEvents 注解测试类。 |
| 2 | 注入当前测试的 ApplicationEvents 实例。 |
| 3 | 使用 ApplicationEvents API 计算发布了多少个 OrderSubmitted 事件。 |
有关 ApplicationEvents API 的更多详细信息,请参阅ApplicationEvents javadoc。