此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

应用程序事件

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事件已发布。

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