应用程序事件
TestContext 框架提供了对记录在 xref page 中发布的应用程序事件的支持,以便在测试中对这些事件进行断言。在单个测试执行期间发布的所有事件均可通过 ApplicationEvents API 获取,该 API 允许你将这些事件作为 java.util.Stream 进行处理。
要在测试中使用ApplicationEvents,请执行以下操作。
-
确保您的测试类已使用
@RecordApplicationEvents进行注解或元注解。 -
确保已注册
ApplicationEventsTestExecutionListener。但请注意,ApplicationEventsTestExecutionListener默认情况下已被注册,仅当您通过@TestExecutionListeners进行了自定义配置且该配置未包含默认监听器时,才需要手动注册。 -
使用 JUnit Jupiter 的 SpringExtension 时, 在
ApplicationEvents、@Test或@BeforeEach方法中声明一个类型为@AfterEach的方法参数。-
由于
ApplicationEvents的作用域限定在当前测试方法的生命周期内,因此这是推荐的做法。
-
-
或者,你可以使用
ApplicationEvents注解标注一个类型为@Autowired的字段,并在你的测试方法和生命周期方法中使用该ApplicationEvents实例。
ApplicationEvents 作为可解析的依赖项(resolvable dependency)注册到 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
Javadoc,以获取有关 ApplicationEvents API 的更多详细信息。