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