應用程式事件

TestContext framework 提供了對 應用程式事件 進行記錄的支援,這些事件釋出在 ApplicationContext 中,以便可以在測試中對這些事件執行斷言。在單個測試執行期間釋出的所有事件都可以透過 ApplicationEvents API 獲取,該 API 允許您將事件作為 java.util.Stream 處理。

要在測試中使用 ApplicationEvents,請執行以下操作。

  • 確保您的測試類使用 @RecordApplicationEvents 進行了註解或元註解。

  • 確保已註冊 ApplicationEventsTestExecutionListener。但請注意,ApplicationEventsTestExecutionListener 預設已註冊,僅當您透過 @TestExecutionListeners 進行的自定義配置不包含預設監聽器時,才需要手動註冊。

  • 使用 @Autowired 註解 ApplicationEvents 型別的欄位,並在測試和生命週期方法(例如 JUnit Jupiter 中的 @BeforeEach@AfterEach 方法)中使用該 ApplicationEvents 例項。

    • 使用 SpringExtension for JUnit Jupiter 時,您可以在測試或生命週期方法中宣告一個 ApplicationEvents 型別的方法引數,作為測試類中 @Autowired 欄位的替代方案。

以下測試類使用 SpringExtension for JUnit Jupiter 和 AssertJ 斷言在呼叫 Spring 管理的元件中的方法時釋出的應用程式事件型別

  • 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 使用 ApplicationEvents API 計算釋出了多少 OrderSubmitted 事件。
@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 API 計算釋出了多少 OrderSubmitted 事件。

有關 ApplicationEvents API 的更多詳細資訊,請參閱 ApplicationEvents javadoc