应用程序事件
TestContext framework 提供了对 应用程序事件 进行记录的支持,这些事件发布在 ApplicationContext
中,以便可以在测试中对这些事件执行断言。在单个测试执行期间发布的所有事件都可以通过 ApplicationEvents
API 获取,该 API 允许您将事件作为 java.util.Stream
处理。
要在测试中使用 ApplicationEvents
,请执行以下操作。
-
确保您的测试类使用
@RecordApplicationEvents
进行了注解或元注解。 -
确保已注册
ApplicationEventsTestExecutionListener
。但请注意,ApplicationEventsTestExecutionListener
默认已注册,仅当您通过@TestExecutionListeners
进行的自定义配置不包含默认监听器时,才需要手动注册。 -
使用
@Autowired
注解ApplicationEvents
类型的字段,并在测试和生命周期方法(例如 JUnit Jupiter 中的@BeforeEach
和@AfterEach
方法)中使用该ApplicationEvents
实例。-
使用 SpringExtension for JUnit Jupiter 时,您可以在测试或生命周期方法中声明一个
ApplicationEvents
类型的方法参数,作为测试类中@Autowired
字段的替代方案。
-
以下测试类使用 SpringExtension
for 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 API 计算发布了多少 OrderSubmitted 事件。 |
@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 API 计算发布了多少 OrderSubmitted 事件。 |
有关 ApplicationEvents
API 的更多详细信息,请参阅 ApplicationEvents
javadoc。