对于最新的稳定版本,请使用 Spring Framework 7.0.6!spring-doc.cadn.net.cn

应用事件

从 Spring Framework 5.3.3 开始,TestContext 框架提供了对记录在 ApplicationContext 中发布的 应用事件 的支持,以便可以在测试中对这些事件进行断言。在单个测试执行期间发布的所有事件都可以通过 ApplicationEvents 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

  • 将类型为ApplicationEvents的字段标注为@Autowired,并在您的测试和生命周期方法(如JUnit Jupiter中的@BeforeEach@AfterEach方法)中使用该实例。spring-doc.cadn.net.cn

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

@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 的更多详细信息。spring-doc.cadn.net.cn