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