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