此版本仍在开发中,尚未稳定。如需最新的稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

应用事件

TestContext 框架提供了对记录在 应用程序事件 中的支持,以便在测试中对这些事件执行断言。单个测试执行期间发布的所有事件都可通过 ApplicationContext API 进行访问,该 API 允许您将事件作为 java.util.Stream 来处理。spring-doc.cadn.net.cn

要在您的测试中使用 ApplicationEvents,请执行以下操作。spring-doc.cadn.net.cn

  • 确保您的测试类使用@RecordApplicationEvents进行注解或元注解。spring-doc.cadn.net.cn

  • 确保 ApplicationEventsTestExecutionListener 已被注册。但是请注意, ApplicationEventsTestExecutionListener 默认已被注册,只有在通过 @TestExecutionListeners 进行自定义配置且不包含默认监听器时才需要手动注册。spring-doc.cadn.net.cn

  • 在使用 JUnit Jupiter的Spring扩展时, 在测试类beforeEachbeforeAll方法中声明一个类型为ApplicationContext的方法参数。spring-doc.cadn.net.cn

    • 因为ApplicationEvents的作用域限制在当前测试方法的生命周期内,这是推荐的做法。spring-doc.cadn.net.cn

  • 另外,您可以在类型为 ApplicationEvents 的字段上使用 @Autowired 注解 并在测试和生命周期方法中使用 ApplicationEvents 的该实例。spring-doc.cadn.net.cn

ApplicationEvents 已经作为 可解析依赖项 注册到了 ApplicationContext 中,其作用域限制在当前测试方法的生命周期内。因此,ApplicationEvents 无法在测试方法的生命周期之外访问,也无法被 @Autowired 到测试类的构造函数中。

以下测试类使用 SpringExtension 用于 JUnit Jupiter 和 AssertJ 来断言在调用 Spring 管理的组件中的方法时发布的应用事件类型:spring-doc.cadn.net.cn

@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {

	@Test
	void submitOrder(@Autowired OrderService service, ApplicationEvents events) { (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(); (3)
		assertThat(numEvents).isEqualTo(1);
	}
}
1 使用 @RecordApplicationEvents 标注测试类。
2 为当前测试注入 ApplicationEvents 实例。
3 使用 ApplicationEvents API 来统计发布了多少个 OrderSubmitted 事件。
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {

	@Test
	fun submitOrder(@Autowired service: OrderService, events: ApplicationEvents) { (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() (3)
		assertThat(numEvents).isEqualTo(1)
	}
}
1 使用 @RecordApplicationEvents 标注测试类。
2 为当前测试注入 ApplicationEvents 实例。
3 使用 ApplicationEvents API 来统计发布了多少个 OrderSubmitted 事件。

查看 ApplicationEvents javadoc 以获取有关 ApplicationEvents API 的更多详细信息。spring-doc.cadn.net.cn