应用事件

自Spring Framework 5.3.3起,TestContext框架提供了对在ApplicationContext中发布的应用事件进行记录的支持,以便在测试中对这些事件进行断言。在执行单个测试期间发布的所有事件都可以通过ApplicationEvents API获得,该API允许您将事件处理为java.util.Stream

要在您的测试中使用ApplicationEvents,请执行以下操作。

  • 确保您的测试类已注解或元注解为@RecordApplicationEvents

  • 确保已注册ApplicationEventsTestExecutionListener。但请注意,默认情况下已注册ApplicationEventsTestExecutionListener,只有在通过@TestExecutionListeners进行自定义配置且未包含默认监听器时才需要手动注册。

  • 使用@Autowired注解一个类型为ApplicationEvents的字段,并在测试和生命周期方法(例如JUnit Jupiter中的@BeforeEach@AfterEach方法)中使用该ApplicationEvents实例。

    • 当使用JUnit Jupiter的SpringExtension时,您可以在测试或生命周期方法中声明一个类型为ApplicationEvents的方法参数,作为测试类中@Autowired字段的替代方法。

以下测试类使用了SpringExtension进行JUnit Jupiter测试,并使用AssertJ来断言在调用Spring管理组件中的方法时发布的应用事件的类型:

  • Java

  • Kotlin

@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {

	@Autowired
	OrderService orderService;

	@Autowired
	ApplicationEvents events; (2)

	@Test
	void submitOrder() {
		// 调用OrderService中发布事件的方法
		orderService.submitOrder(new Order(/* ... */));
		// 验证是否发布了OrderSubmitted事件
		long numEvents = events.stream(OrderSubmitted.class).count(); (3)
		assertThat(numEvents).isEqualTo(1);
	}
}
1 使用@RecordApplicationEvents注解测试类。
2 为当前测试注入ApplicationEvents实例。
3 使用ApplicationEvents API计算发布的OrderSubmitted事件数量。
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {

	@Autowired
	lateinit var orderService: OrderService

	@Autowired
	lateinit var events: ApplicationEvents (2)

	@Test
	fun submitOrder() {
		// 调用OrderService中发布事件的方法
		orderService.submitOrder(Order(/* ... */))
		// 验证是否发布了OrderSubmitted事件
		val numEvents = events.stream(OrderSubmitted::class).count() (3)
		assertThat(numEvents).isEqualTo(1)
	}
}
1 使用@RecordApplicationEvents注解测试类。
2 为当前测试注入ApplicationEvents实例。
3 使用ApplicationEvents API计算发布的OrderSubmitted事件数量。

有关ApplicationEvents API的更多详细信息,请参阅ApplicationEvents javadoc