此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 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

ApplicationEventsApplicationContext作为可解析的 依赖项,其范围限定为当前测试方法的生命周期。因此ApplicationEvents不能在测试方法的生命周期之外访问,也不能@Autowired到测试类的构造函数中。

以下测试类使用SpringExtensionJUnit 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用于计算数量的 APIOrderSubmitted事件已发布。
@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用于计算数量的 APIOrderSubmitted事件已发布。

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