|
此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
应用程序事件
TestContext 框架支持记录在ApplicationContext以便可以针对这些
测试中的事件。在执行单个测试期间发布的所有事件都已生成
可通过ApplicationEventsAPI,允许您将事件处理为java.util.Stream.
使用ApplicationEvents在测试中,执行以下作。
-
确保测试类已使用
@RecordApplicationEvents. -
确保
ApplicationEventsTestExecutionListener已注册。但是请注意, 那ApplicationEventsTestExecutionListener默认注册,只需要 如果您通过@TestExecutionListeners不包括默认侦听器。 -
当使用 SpringExtension for JUnit Jupiter 时, 声明类型为
ApplicationEvents在@Test,@BeforeEach或@AfterEach方法。-
因为
ApplicationEvents范围限定为当前测试方法的生命周期,则此 是推荐的方法。
-
-
或者,您可以注释类型
ApplicationEvents跟@Autowired并使用ApplicationEvents在测试和生命周期方法中。
ApplicationEvents在ApplicationContext作为可解析的
依赖项,其范围限定为当前测试方法的生命周期。因此ApplicationEvents不能在测试方法的生命周期之外访问,也不能@Autowired到测试类的构造函数中。 |
以下测试类使用SpringExtensionJUnit Jupiter 和 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用于计算数量的 APIOrderSubmitted事件已发布。 |
@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用于计算数量的 APIOrderSubmitted事件已发布。 |
请参阅ApplicationEventsJava文档有关ApplicationEvents应用程序接口。