|
对于最新稳定版本,请使用 Spring Framework 7.0.6! |
应用程序事件
自 Spring Framework 5.3.3 起,TestContext 框架提供了对在 xref page 中发布的应用事件进行记录的支持,以便在测试中对这些事件执行断言。单个测试执行期间发布的所有事件均可通过 ApplicationEvents API 获取,该 API 允许你将这些事件作为 java.util.Stream 进行处理。
要在测试中使用ApplicationEvents,请执行以下操作。
-
确保您的测试类已使用
@RecordApplicationEvents进行注解或元注解。 -
确保已注册
ApplicationEventsTestExecutionListener。但请注意,ApplicationEventsTestExecutionListener默认情况下已被注册,仅当您通过@TestExecutionListeners进行了自定义配置且该配置未包含默认监听器时,才需要手动注册。 -
使用
ApplicationEvents注解标注一个类型为@Autowired的字段,并在您的测试方法和生命周期方法(例如 JUnit Jupiter 中的ApplicationEvents和@BeforeEach方法)中使用该@AfterEach实例。-
使用 JUnit Jupiter 的 SpringExtension 时,您可以在测试方法或生命周期方法中声明一个类型为
ApplicationEvents的方法参数,作为在测试类中使用@Autowired字段的替代方式。
-
以下测试类使用 JUnit Jupiter 的 SpringExtension 和
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
Javadoc,以获取有关 ApplicationEvents API 的更多详细信息。