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

应用程序事件

从 Spring Framework 5.3.3 开始,TestContext 框架支持记录在ApplicationContext以便可以针对 测试。在执行单个测试期间发布的所有事件都可通过 这ApplicationEventsAPI 允许您将事件作为java.util.Stream.spring-doc.cadn.net.cn

要使用ApplicationEvents在测试中,执行以下作。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计算数量 APIOrderSubmitted事件被公布。
@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计算数量 APIOrderSubmitted事件被公布。

请参阅ApplicationEventsJavadoc有关ApplicationEvents应用程序接口。spring-doc.cadn.net.cn