應用程式事件

TestContext 框架提供記錄 應用程式事件 的支援,這些事件發佈在 ApplicationContext 中,以便可以在測試中針對這些事件執行斷言。在單一測試執行期間發佈的所有事件都可透過 ApplicationEvents API 取得,該 API 允許您將事件作為 java.util.Stream 處理。

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

  • 確保您的測試類別已使用 @RecordApplicationEvents 進行註解或 Meta 註解。

  • 確保已註冊 ApplicationEventsTestExecutionListener。但是請注意,ApplicationEventsTestExecutionListener 預設為已註冊,只有當您透過 @TestExecutionListeners 進行自訂組態且不包含預設 Listener 時,才需要手動註冊。

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

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

以下測試類別使用 JUnit Jupiter 的 SpringExtensionAssertJ 來斷言在 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 javadoc,以取得有關 ApplicationEvents API 的更多詳細資訊。