應用程式事件
TestContext 框架提供支援來記錄在 ApplicationContext 中釋出的應用事件,以便在測試中對這些事件進行斷言。在單個測試執行期間釋出的所有事件都透過 ApplicationEvents API 提供,該 API 允許您將事件作為 java.util.Stream 進行處理。
要在測試中使用 ApplicationEvents,請執行以下操作。
-
確保您的測試類使用
@RecordApplicationEvents進行了註解或元註解。 -
確保
ApplicationEventsTestExecutionListener已註冊。然而請注意,ApplicationEventsTestExecutionListener預設是註冊的,只有當您透過@TestExecutionListeners進行的自定義配置不包含預設監聽器時,才需要手動註冊。 -
當使用 JUnit Jupiter 的 Spring 擴充套件時,在
@Test、@BeforeEach或@AfterEach方法中宣告一個ApplicationEvents型別的方法引數。-
由於
ApplicationEvents的作用域限定於當前測試方法的生命週期,因此這是推薦的方法。
-
-
或者,您可以使用
@Autowired註解一個ApplicationEvents型別的欄位,並在測試和生命週期方法中使用該ApplicationEvents例項。
ApplicationEvents 在 ApplicationContext 中註冊為可解析依賴項,其作用域限定於當前測試方法的生命週期。因此,ApplicationEvents 不能在測試方法的生命週期之外訪問,也不能透過 @Autowired 注入到測試類的建構函式中。 |
以下測試類使用 JUnit Jupiter 的 SpringExtension 和 AssertJ 來斷言在呼叫 Spring 管理元件中的方法時釋出的應用事件的型別
-
Java
-
Kotlin
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents (1)
class OrderServiceTests {
@Test
void submitOrder(@Autowired OrderService service, ApplicationEvents events) { (2)
// Invoke method in OrderService that publishes an event
service.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 {
@Test
fun submitOrder(@Autowired service: OrderService, events: ApplicationEvents) { (2)
// Invoke method in OrderService that publishes an event
service.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。