このバージョンはまだ開発中であり、まだ安定しているとは見なされていません。最新の安定バージョンについては、Spring Framework 6.2.12 を使用してください!

アプリケーションイベント

TestContext フレームワークは、ApplicationContext で公開されたアプリケーションイベントの記録をサポートしており、テスト内でそれらのイベントに対してアサーションを実行できます。単一のテスト実行中に公開されたすべてのイベントは、ApplicationEvents API を介して利用可能になり、イベントを java.util.Stream として処理できます。

テストで ApplicationEvents を使用するには、次のようにします。

  • テストクラスに @RecordApplicationEvents アノテーションが付けられているかメタアノテーションが付けられていることを確認してください。

  • ApplicationEventsTestExecutionListener が登録されていることを確認してください。ただし、ApplicationEventsTestExecutionListener はデフォルトで登録されており、デフォルトのリスナーを含まない @TestExecutionListeners を介したカスタム構成がある場合にのみ、手動で登録する必要があることに注意してください。

  • JUnit Jupiter 用 SpringExtension を使用する場合は、@Test@BeforeEach、または @AfterEach メソッドで ApplicationEvents 型のメソッドパラメーターを宣言します。

    • ApplicationEvents は現在のテストメソッドのライフサイクルにスコープが設定されているため、これが推奨されるアプローチです。

  • あるいは、ApplicationEvents 型のフィールドに @Autowired のアノテーションを付け、テストおよびライフサイクルメソッドで 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 インスタンスを注入します。
3ApplicationEvents 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 インスタンスを注入します。
3ApplicationEvents API を使用して、公開された OrderSubmitted イベントの数をカウントします。

ApplicationEvents API の詳細については、ApplicationEvents javadoc を参照してください。