此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.1.10Spring中文文档

此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.1.10Spring中文文档

从 Spring Framework 5.3.3 开始,TestContext 框架支持记录在 测试。在执行单个测试期间发布的所有事件都可通过以下方式获得 允许您将事件作为 .ApplicationContextApplicationEventsjava.util.StreamSpring中文文档

若要在测试中使用,请执行以下操作。ApplicationEventsSpring中文文档

  • 确保测试类已使用 @RecordApplicationEvents 进行注释或元注释。Spring中文文档

  • 确保已注册。但是请注意, 默认注册,只需要 如果您有自定义配置,则手动注册,不包括默认侦听器。ApplicationEventsTestExecutionListenerApplicationEventsTestExecutionListener@TestExecutionListenersSpring中文文档

  • 在测试和生命周期方法(例如 JUnit Jupiter 中的 和 方法)中使用该类型的字段来注释该字段。ApplicationEvents@AutowiredApplicationEvents@BeforeEach@AfterEachSpring中文文档

以下测试类使用 for JUnit、Jupiter 和 AssertJ 来断言应用程序事件的类型 在 Spring 托管组件中调用方法时发布:SpringExtensionSpring中文文档

@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 使用 API 计算已发布的事件数。ApplicationEventsOrderSubmitted
@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 使用 API 计算已发布的事件数。ApplicationEventsOrderSubmitted
1 用 批注测试类。@RecordApplicationEvents
2 注入当前测试的实例。ApplicationEvents
3 使用 API 计算已发布的事件数。ApplicationEventsOrderSubmitted
1 用 批注测试类。@RecordApplicationEvents
2 注入当前测试的实例。ApplicationEvents
3 使用 API 计算已发布的事件数。ApplicationEventsOrderSubmitted

有关 API 的更多详细信息,请参阅 ApplicationEvents javadocApplicationEventsSpring中文文档