应用程序事件
TestContext 框架支持记录在ApplicationContext
以便可以针对
测试。在执行单个测试期间发布的所有事件都可通过
这ApplicationEvents
API 允许您将事件作为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 事件被公布。 |
请参阅ApplicationEvents
Javadoc有关ApplicationEvents
应用程序接口。