|
此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.7! |
应用程序事件
从 Spring Framework 5.3.3 开始,TestContext 框架支持记录在ApplicationContext以便可以针对
测试。在执行单个测试期间发布的所有事件都可通过
这ApplicationEventsAPI 允许您将事件作为java.util.Stream.
要使用ApplicationEvents在测试中,执行以下作。
-
确保您的测试类带有 Comments 或 Meta-Annoting。
@RecordApplicationEvents. -
确保
ApplicationEventsTestExecutionListener已注册。但是请注意, 那ApplicationEventsTestExecutionListener默认注册,只需要 如果您通过@TestExecutionListeners这不包括默认侦听器。 -
对 type 为
ApplicationEvents跟@Autowired并使用ApplicationEvents在测试和生命周期方法(例如@BeforeEach和@AfterEach方法)。-
当使用 SpringExtension for JUnit Jupiter 时,你可以声明一个方法 type 为
ApplicationEvents在 test 或 lifecycle 方法中作为替代方法 更改为@Autowired字段。
-
以下测试类使用SpringExtension用于 JUnit Jupiter 和 AssertJ 断言应用程序事件的类型
在 Spring 管理的组件中调用方法时发布:
-
Java
-
Kotlin
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {
@Autowired
OrderService orderService;
@Autowired
ApplicationEvents events; (2)
@Test
void submitOrder() {
// Invoke method in OrderService that publishes an event
orderService.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 {
@Autowired
lateinit var orderService: OrderService
@Autowired
lateinit var events: ApplicationEvents (2)
@Test
fun submitOrder() {
// Invoke method in OrderService that publishes an event
orderService.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事件被公布。 |
请参阅ApplicationEventsJavadoc有关ApplicationEvents应用程序接口。