应用程序事件
TestContext 框架提供了记录在 ApplicationContext
中发布的
应用程序事件
的支持,以便在测试中对这些事件执行断言。在单个测试执行期间发布的所有事件都通过
ApplicationEvents
API 提供,该 API 允许您将事件作为
java.util.Stream
进行处理。
要在测试中使用 ApplicationEvents
,请执行以下操作。
-
确保您的测试类使用
@RecordApplicationEvents
进行了注解或元注解。 -
确保
ApplicationEventsTestExecutionListener
已注册。但请注意,ApplicationEventsTestExecutionListener
默认已注册,仅当您通过@TestExecutionListeners
进行的自定义配置不包含默认监听器时才需要 手动注册。 -
当使用 JUnit Jupiter 的 SpringExtension 时,在
@Test
、@BeforeEach
或@AfterEach
方法中声明一个ApplicationEvents
类型的方法参数。-
由于
ApplicationEvents
的作用域限定为当前测试方法的生命周期,因此 这是推荐的方法。
-
-
或者,您可以使用
@Autowired
注解ApplicationEvents
类型的字段, 并在您的测试和生命周期方法中使用该ApplicationEvents
实例。
|
以下测试类使用 JUnit Jupiter 的 SpringExtension
和
AssertJ 来断言在调用 Spring 管理组件中的方法时发布的
应用程序事件的类型:
- Java
-
@SpringJUnitConfig(/* ... */) @RecordApplicationEvents [id="CO1-1"][id="CO1-1"][id="CO1-1"](1) class OrderServiceTests { @Test void submitOrder(@Autowired OrderService service, ApplicationEvents events) { [id="CO1-2"][id="CO1-2"][id="CO1-2"](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(); [id="CO1-3"][id="CO1-3"][id="CO1-3"](3) assertThat(numEvents).isEqualTo(1); } }
<1> 使用 `@RecordApplicationEvents` 注解测试类。 <1> 注入当前测试的 `ApplicationEvents` 实例。 <1> 使用 `ApplicationEvents` API 计算发布了多少 `OrderSubmitted` 事件。
- Kotlin
-
@SpringJUnitConfig(/* ... */) @RecordApplicationEvents [id="CO2-1"][id="CO1-4"][id="CO2-1"](1) class OrderServiceTests { @Test fun submitOrder(@Autowired service: OrderService, events: ApplicationEvents) { [id="CO2-2"][id="CO1-5"][id="CO2-2"](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() [id="CO2-3"][id="CO1-6"][id="CO2-3"](3) assertThat(numEvents).isEqualTo(1) } }
<1> 使用 `@RecordApplicationEvents` 注解测试类。 <1> 注入当前测试的 `ApplicationEvents` 实例。 <1> 使用 `ApplicationEvents` API 计算发布了多少 `OrderSubmitted` 事件。
有关 ApplicationEvents
API 的更多详细信息,请参阅
ApplicationEvents
javadoc。