应用程序事件

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事件被公布。

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


APP信息