从 Spring Framework 5.3.3 开始,TestContext 框架支持记录在
测试。在执行单个测试期间发布的所有事件都可通过
允许您将事件作为 .ApplicationContextApplicationEventsjava.util.Stream
要在测试中使用,请执行以下操作。ApplicationEvents
- 
确保您的测试类使用
@RecordApplicationEvents进行批注或元批注。 - 
确保 已注册。但是请注意, 默认注册,只需要 手动注册(如果您有自定义配置),则不包含默认侦听器。
ApplicationEventsTestExecutionListenerApplicationEventsTestExecutionListener@TestExecutionListeners - 
在测试和生命周期方法(例如 JUnit Jupiter 中的 and methods)中使用 type of 的字段注释并使用该实例。
ApplicationEvents@AutowiredApplicationEvents@BeforeEach@AfterEach- 
当使用 SpringExtension for JUnit Jupiter 时,你可以声明一个方法 parameter 作为替代方法 设置为 test 类中的字段。
ApplicationEvents@Autowired 
 - 
 
以下测试类使用 for JUnit、Jupiter 和 AssertJ 来断言应用程序事件的类型
在 Spring 管理的组件中调用方法时发布:SpringExtension
- 
Java
 - 
Kotlin
 
@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 javadoc。ApplicationEvents