Spring Boot アプリケーションのテスト

Spring Boot アプリケーションは Spring ApplicationContext であるため、バニラ Spring コンテキストで通常行うことを超えてテストするために特別なことは何もする必要はありません。

Spring Boot の外部プロパティ、ロギング、その他の機能は、SpringApplication を使用して作成する場合にのみ、デフォルトでコンテキストにインストールされます。

Spring Boot は @SpringBootTest アノテーションを提供します。これは、Spring Boot 機能が必要な場合に、標準の spring-test@ContextConfiguration アノテーションの代わりに使用できます。アノテーションは、SpringApplication を介してテストで使用される ApplicationContext を作成することによって機能します@SpringBootTest に加えて、アプリケーションのより具体的なスライステストするために、他の多くのアノテーションも提供されています。

JUnit 4 を使用している場合は、@RunWith(SpringRunner.class) もテストに追加することを忘れないでください。そうしないと、アノテーションが無視されます。JUnit 5 を使用している場合は、同等の @ExtendWith(SpringExtension.class) を @SpringBootTest として追加する必要はなく、他の @…​Test アノテーションにはすでにアノテーションが付けられています。

デフォルトでは、@SpringBootTest はサーバーを起動しません。@SpringBootTest の webEnvironment 属性を使用して、テストの実行方法をさらに絞り込むことができます。

  • MOCK(デフォルト): Web ApplicationContext をロードし、モック Web 環境を提供します。このアノテーションを使用すると、組み込みサーバーは起動しません。Web 環境がクラスパスで利用できない場合、このモードは通常の非 Web ApplicationContext の作成に透過的にフォールバックします。Web アプリケーションのモックベースのテストのために、@AutoConfigureMockMvc または @AutoConfigureWebTestClient と組み合わせて使用できます。

  • RANDOM_PORTWebServerApplicationContext をロードし、実際の Web 環境を提供します。組み込みサーバーが起動され、ランダムポートでリッスンします。

  • DEFINED_PORTWebServerApplicationContext をロードし、実際の Web 環境を提供します。組み込みサーバーが開始され、定義済みのポート(application.properties から)またはデフォルトのポート 8080 で listen します。

  • NONESpringApplication を使用して ApplicationContext をロードしますが Web 環境(モックまたはその他)を提供しません。

テストが @Transactional の場合、デフォルトで各テストメソッドの最後にトランザクションをロールバックします。ただし、RANDOM_PORT または DEFINED_PORT のいずれかでこの配置を使用すると、実際のサーブレット環境が暗黙的に提供されるため、HTTP クライアントとサーバーは別々のスレッドで、別々のトランザクションで実行されます。この場合、サーバーで開始されたトランザクションはロールバックしません。
@SpringBootTest と webEnvironment = WebEnvironment.RANDOM_PORT は、アプリケーションが管理サーバーに異なるポートを使用している場合、別のランダムポートで管理サーバーを起動します。

Web アプリケーション型の検出

Spring MVC が使用可能な場合、通常の MVC ベースのアプリケーションコンテキストが構成されます。Spring WebFlux しかない場合は、それを検出し、代わりに WebFlux ベースのアプリケーションコンテキストを構成します。

両方が存在する場合、Spring MVC が優先されます。このシナリオでリアクティブ Web アプリケーションをテストする場合は、spring.main.web-application-type プロパティを設定する必要があります。

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest(properties = "spring.main.web-application-type=reactive")
class MyWebFluxTests {

	// ...

}

テスト構成の検出

Spring Test フレームワークに精通している場合は、ロードする Spring @Configuration を指定するために @ContextConfiguration(classes=…​) を使用することに慣れているかもしれません。または、テスト内でネストされた @Configuration クラスを頻繁に使用した可能性があります。

Spring Boot アプリケーションをテストする場合、これは多くの場合必要ありません。Spring Boot の @*Test アノテーションは、明示的に定義しない限り、プライマリ設定を自動的に検索します。

検索アルゴリズムは、@SpringBootApplication または @SpringBootConfiguration のアノテーションが付けられたクラスが見つかるまで、テストを含むパッケージから動作します。コードを実用的なメソッドで構造化している限り、メインの設定は通常見つかります。

@SpringBootApplication の基礎となるコンポーネントスキャン構成は、スライスが期待どおりに機能することを確認するために使用される除外フィルターを定義します。@SpringBootApplication アノテーション付きクラスで明示的な @ComponentScan ディレクティブを使用している場合は、これらのフィルターが無効になることに注意してください。スライスを使用している場合は、再度定義する必要があります。

プライマリ設定をカスタマイズする場合は、ネストされた @TestConfiguration クラスを使用できます。アプリケーションのプライマリ設定の代わりに使用されるネストされた @Configuration クラスとは異なり、ネストされた @TestConfiguration クラスはアプリケーションのプライマリ設定に加えて使用されます。

Spring のテストフレームワークは、テスト間のアプリケーションコンテキストをキャッシュします。テストが同じ構成を共有している限り(検出方法に関係なく)、コンテキストをロードする潜在的に時間のかかるプロセスは 1 回しか発生しません。

テストコンフィギュレーションのメインメソッドの使用

通常、@SpringBootTest によって検出されたテスト構成は、メインの @SpringBootApplication になります。ほとんどの適切に構造化されたアプリケーションでは、この構成クラスには、アプリケーションの起動に使用される main メソッドも含まれます。

例: 以下は、典型的な Spring Boot アプリケーションの非常に一般的なコードパターンです。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {

	public static void main(String[] args) {
		SpringApplication.run(MyApplication.class, args);
	}

}

上記の例では、main メソッドは SpringApplication.run への委譲以外は何もしません。ただし、SpringApplication.run を呼び出す前にカスタマイズを適用する、より複雑な main メソッドを持つことは可能です。

例: バナーモードを変更し、追加のプロファイルを設定するアプリケーションは次のとおりです。

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {

	public static void main(String[] args) {
		SpringApplication application = new SpringApplication(MyApplication.class);
		application.setBannerMode(Banner.Mode.OFF);
		application.setAdditionalProfiles("myprofile");
		application.run(args);
	}

}

main メソッドのカスタマイズは、結果の ApplicationContext に影響を与える可能性があるため、main メソッドを使用して、テストで使用される ApplicationContext を作成することもできます。デフォルトでは、@SpringBootTest は main メソッドを呼び出さず、代わりにクラス自体を直接使用して ApplicationContext を作成します。

この動作を変更する場合は、@SpringBootTest の useMainMethod 属性を UseMainMethod.ALWAYS または UseMainMethod.WHEN_AVAILABLE に変更できます。ALWAYS に設定すると、main メソッドが見つからない場合、テストは失敗します。WHEN_AVAILABLE に設定すると、main メソッドが使用可能であればそれが使用されます。それ以外の場合は、標準の読み込みメカニズムが使用されます。

例: 次のテストは、ApplicationContext を作成するために MyApplication の main メソッドを呼び出します。メインメソッドが追加のプロファイルを設定すると、ApplicationContext の開始時にそれらがアクティブになります。

import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.UseMainMethod;

@SpringBootTest(useMainMethod = UseMainMethod.ALWAYS)
class MyApplicationTests {

	@Test
	void exampleTest() {
		// ...
	}

}

テスト構成の除外

アプリケーションがコンポーネントスキャンを使用している場合(たとえば、@SpringBootApplication または @ComponentScan を使用している場合)、特定のテスト用に作成した最上位の構成クラスが誤ってどこでも取得される可能性があります。

前に見たように、@TestConfiguration をテストの内部クラスで使用して、主要な構成をカスタマイズできます。@TestConfiguration は最上位クラスでも使用可能です。これは、そのクラスがスキャンによって検出されるべきではないことを示します。次に、次の例に示すように、必要な場所にクラスを明示的にインポートできます。

import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;

@SpringBootTest
@Import(MyTestsConfiguration.class)
class MyTests {

	@Test
	void exampleTest() {
		// ...
	}

}
@ComponentScan を直接使用する場合(つまり、@SpringBootApplication を介さずに)、TypeExcludeFilter を登録する必要があります。詳細については、Javadoc を参照してください。
インポートされた @TestConfiguration は内部クラスの @TestConfiguration よりも先に処理され、インポートされた @TestConfiguration はコンポーネントのスキャンで検出された構成よりも前に処理されます。一般に、この順序の違いは目立った影響はありませんが、Bean のオーバーライドに依存している場合は注意が必要です。

アプリケーション引数の使用

アプリケーションが引数を必要とする場合は、args 属性を使用して @SpringBootTest に引数を挿入させることができます。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.test.context.SpringBootTest;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(args = "--app.test=one")
class MyApplicationArgumentTests {

	@Test
	void applicationArgumentsPopulated(@Autowired ApplicationArguments args) {
		assertThat(args.getOptionNames()).containsOnly("app.test");
		assertThat(args.getOptionValues("app.test")).containsOnly("one");
	}

}

モック環境でのテスト

デフォルトでは、@SpringBootTest はサーバーを起動しませんが、代わりに Web エンドポイントをテストするためのモック環境をセットアップします。

次の例に示すように、Spring MVC を使用すると、MockMvc または WebTestClient を使用して Web エンドポイントにクエリを実行できます。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
class MyMockMvcTests {

	@Test
	void testWithMockMvc(@Autowired MockMvc mvc) throws Exception {
		mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World"));
	}

	// If Spring WebFlux is on the classpath, you can drive MVC tests with a WebTestClient
	@Test
	void testWithWebTestClient(@Autowired WebTestClient webClient) {
		webClient
				.get().uri("/")
				.exchange()
				.expectStatus().isOk()
				.expectBody(String.class).isEqualTo("Hello World");
	}

}
完全な ApplicationContext を開始せずに Web レイヤーのみに焦点を合わせたい場合は、代わりに @WebMvcTest の使用を検討してください

Spring WebFlux エンドポイントでは、次の例に示すように WebTestClient を使用できます。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.reactive.server.WebTestClient;

@SpringBootTest
@AutoConfigureWebTestClient
class MyMockWebTestClientTests {

	@Test
	void exampleTest(@Autowired WebTestClient webClient) {
		webClient
			.get().uri("/")
			.exchange()
			.expectStatus().isOk()
			.expectBody(String.class).isEqualTo("Hello World");
	}

}

モック環境内でのテストは、通常、完全なサーブレットコンテナーで実行するよりも高速です。ただし、モックは Spring MVC レイヤーで発生するため、下位レベルのサーブレットコンテナーの動作に依存するコードを MockMvc で直接テストすることはできません。

例: Spring Boot のエラー処理は、サーブレットコンテナーによって提供される「エラーページ」サポートに基づいています。つまり、MVC レイヤーのスローをテストして例外を期待どおりに処理することはできますが、特定のカスタムエラーページがレンダリングされることを直接テストすることはできません。これらの下位レベルの関心事をテストする必要がある場合は、次のセクションで説明するように、完全に実行されているサーバーを起動できます。

実行中のサーバーでのテスト

完全に稼働しているサーバーを起動する必要がある場合は、ランダムなポートを使用することをお勧めします。@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) を使用すると、テストを実行するたびに使用可能なポートがランダムに選択されます。

@LocalServerPort アノテーションを使用して、実際に使用されるポートをテストに挿入できます。便宜上、開始されたサーバーに対して REST 呼び出しを行う必要があるテストでは、さらに @Autowire と WebTestClient を実行できます。これにより、実行中のサーバーへの相対リンクが解決され、次の例に示すように、レスポンスを検証するための専用 API が付属します。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.web.reactive.server.WebTestClient;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MyRandomPortWebTestClientTests {

	@Test
	void exampleTest(@Autowired WebTestClient webClient) {
		webClient
			.get().uri("/")
			.exchange()
			.expectStatus().isOk()
			.expectBody(String.class).isEqualTo("Hello World");
	}

}
WebTestClient は、テストクラスに @AutoConfigureWebTestClient アノテーションを付けることで、モック環境でも使用でき、サーバーを実行する必要がなくなります。

この設定では、クラスパスに spring-webflux が必要です。webflux を追加できない、または追加しない場合、Spring Boot は TestRestTemplate 機能も提供します。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MyRandomPortTestRestTemplateTests {

	@Test
	void exampleTest(@Autowired TestRestTemplate restTemplate) {
		String body = restTemplate.getForObject("/", String.class);
		assertThat(body).isEqualTo("Hello World");
	}

}

WebTestClient のカスタマイズ

WebTestClient Bean をカスタマイズするには、WebTestClientBuilderCustomizer Bean を構成します。このような Bean は、WebTestClient の作成に使用される WebTestClient.Builder で呼び出されます。

JMX を使用する

テストコンテキストフレームワークはコンテキストをキャッシュするため、JMX はデフォルトで無効になり、同一ドメインに同一のコンポーネントが登録されないようにします。そのようなテストが MBeanServer にアクセスする必要がある場合、同様にダーティマークを付けることを検討してください。

import javax.management.MBeanServer;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(properties = "spring.jmx.enabled=true")
@DirtiesContext
class MyJmxTests {

	@Autowired
	private MBeanServer mBeanServer;

	@Test
	void exampleTest() {
		assertThat(this.mBeanServer.getDomains()).contains("java.lang");
		// ...
	}

}

観測値の使用

スライスされたテストに @AutoConfigureObservability のアノテーションを付けると、ObservationRegistry が自動構成されます。

メトリクスの使用

クラスパスに関係なく、@SpringBootTest を使用する場合、メモリ内でバックアップされているものを除いて、メーターレジストリは自動構成されません。

統合テストの一環としてメトリクスを別のバックエンドにエクスポートする必要がある場合は、@AutoConfigureObservability でアノテーションを付けます。

スライスされたテストに @AutoConfigureObservability のアノテーションを付けると、メモリ内 MeterRegistry が自動構成されます。スライステストでのデータのエクスポートは、@AutoConfigureObservability アノテーションではサポートされていません。

トレースの使用

クラスパスに関係なく、@SpringBootTest を使用する場合、データをレポートするトレースコンポーネントは自動構成されません。

統合テストの一部としてこれらのコンポーネントが必要な場合は、テストに @AutoConfigureObservability のアノテーションを付けます。

独自のレポートコンポーネント (カスタム SpanExporter または SpanHandler など) を作成しており、テストでアクティブにしたくない場合は、@ConditionalOnEnabledTracing アノテーションを使用して無効にすることができます。

スライスされたテストに @AutoConfigureObservability のアノテーションを付けると、no-op Tracer が自動構成されます。スライステストでのデータのエクスポートは、@AutoConfigureObservability アノテーションではサポートされていません。

Bean のモックとスパイ

テストを実行するとき、アプリケーションコンテキスト内の特定のコンポーネントをモックする必要がある場合があります。例: 開発中は利用できないリモートサービスのファサードがある場合があります。モックは、実際の環境では引き起こしにくい障害をシミュレートする場合にも役立ちます。

Spring Boot には、ApplicationContext 内の Bean の Mockito モックを定義するために使用できる @MockBean アノテーションが含まれています。アノテーションを使用して、新しい Bean を追加したり、単一の既存の Bean 定義を置き換えることができます。アノテーションは、テストクラス、テスト内のフィールド、@Configuration クラスとフィールドで直接使用できます。フィールドで使用すると、作成されたモックのインスタンスも注入されます。モック Bean は、各テストメソッドの後に自動的にリセットされます。

テストで Spring Boot のテストアノテーションの 1 つ(@SpringBootTest など)を使用する場合、この機能は自動的に有効になります。この機能を別の配置で使用するには、次の例に示すように、リスナーを明示的に追加する必要があります。

import org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener;
import org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;

@ContextConfiguration(classes = MyConfig.class)
@TestExecutionListeners({ MockitoTestExecutionListener.class, ResetMocksTestExecutionListener.class })
class MyTests {

	// ...

}

次の例では、既存の RemoteService Bean をモック実装に置き換えます。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;

@SpringBootTest
class MyTests {

	@Autowired
	private Reverser reverser;

	@MockBean
	private RemoteService remoteService;

	@Test
	void exampleTest() {
		given(this.remoteService.getValue()).willReturn("spring");
		String reverse = this.reverser.getReverseValue(); // Calls injected RemoteService
		assertThat(reverse).isEqualTo("gnirps");
	}

}
@MockBean を使用して、アプリケーションコンテキストのリフレッシュ中に実行される Bean の動作を模倣することはできません。テストが実行されるまでに、アプリケーションコンテキストのリフレッシュが完了し、モック動作を構成するには遅すぎます。この状況では、@Bean メソッドを使用してモックを作成および構成することをお勧めします。

さらに、@SpyBean を使用して、既存の Bean を Mockito spy でラップすることができます。詳細については、Javadoc を参照してください。

Spring のテストフレームワークはテスト間でアプリケーションコンテキストをキャッシュし、同じ構成を共有するテストでコンテキストを再利用しますが、@MockBean または @SpyBean の使用はキャッシュキーに影響し、コンテキストの数を増やす可能性が高くなります。
@SpyBean を使用して、名前でパラメーターを参照する @Cacheable メソッドで Bean をスパイする場合、アプリケーションは -parameters でコンパイルする必要があります。これにより、Bean がスパイされると、パラメーター名がキャッシュインフラストラクチャで使用可能になります。
@SpyBean を使用して、Spring によってプロキシされている Bean をスパイしている場合、given または when を使用して期待値を設定する場合など、状況によっては Spring のプロキシを削除する必要がある場合があります。これを行うには、AopTestUtils.getTargetObject(yourProxiedSpy) を使用します。

自動構成されたテスト

Spring Boot の自動構成システムは、アプリケーションではうまく機能しますが、テストには少し多すぎる場合があります。多くの場合、アプリケーションの「スライス」をテストするために必要な構成部分のみをロードすると役立ちます。例: Spring MVC コントローラーが URL を正しくマッピングしていることをテストしたい場合があり、それらのテストにデータベース呼び出しを含めたくない場合、または JPA エンティティをテストしたい場合、それらのテストの実行時に Web レイヤーに関心がない場合 .

spring-boot-test-autoconfigure モジュールには、このような「スライス」を自動的に構成するために使用できる多くのアノテーションが含まれています。それぞれが同様に機能し、ApplicationContext をロードする @…​Test アノテーションと、自動構成設定のカスタマイズに使用できる 1 つ以上の @AutoConfigure…​ アノテーションを提供します。

各スライスは、コンポーネントスキャンを適切なコンポーネントに制限し、非常に制限された自動構成クラスのセットをロードします。それらのいずれかを除外する必要がある場合、ほとんどの @…​Test アノテーションは excludeAutoConfiguration 属性を提供します。または、@ImportAutoConfiguration#exclude を使用できます。
1 つのテストで複数の @…​Test アノテーションを使用して複数の「スライス」を含めることはサポートされていません。複数の「スライス」が必要な場合は、@…​Test アノテーションの 1 つを選択し、他の「スライス」の @AutoConfigure…​ アノテーションを手動で含めます。
@AutoConfigure…​ アノテーションを標準の @SpringBootTest アノテーションとともに使用することもできます。アプリケーションの「スライス」に興味はないが、自動構成されたテスト Bean の一部が必要な場合は、この組み合わせを使用できます。

自動構成された JSON テスト

オブジェクトの JSON 直列化と逆直列化が期待どおりに機能することをテストするには、@JsonTest アノテーションを使用できます。@JsonTest は、使用可能なサポートされている JSON マッパーを自動構成します。これは、次のライブラリのいずれかです。

  • Jackson ObjectMapper@JsonComponent Bean および Jackson Modules

  • Gson

  • Jsonb

@JsonTest によって有効になる自動構成のリストは付録に記載されています。

自動構成の要素を構成する必要がある場合は、@AutoConfigureJsonTesters アノテーションを使用できます。

Spring Boot には、JSONAssert および JsonPath ライブラリと連携して JSON が期待どおりに表示されることを確認する AssertJ ベースのヘルパーが含まれています。JacksonTesterGsonTesterJsonbTesterBasicJsonTester クラスは、それぞれ Jackson、Gson、Jsonb、Strings に使用できます。@JsonTest を使用する場合、テストクラスのヘルパーフィールドはすべて @Autowired にすることができます。次の例は、Jackson のテストクラスを示しています。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;

import static org.assertj.core.api.Assertions.assertThat;

@JsonTest
class MyJsonTests {

	@Autowired
	private JacksonTester<VehicleDetails> json;

	@Test
	void serialize() throws Exception {
		VehicleDetails details = new VehicleDetails("Honda", "Civic");
		// Assert against a `.json` file in the same package as the test
		assertThat(this.json.write(details)).isEqualToJson("expected.json");
		// Or use JSON path based assertions
		assertThat(this.json.write(details)).hasJsonPathStringValue("@.make");
		assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make").isEqualTo("Honda");
	}

	@Test
	void deserialize() throws Exception {
		String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
		assertThat(this.json.parse(content)).isEqualTo(new VehicleDetails("Ford", "Focus"));
		assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford");
	}

}
JSON ヘルパークラスは、標準の単体テストで直接使用することもできます。これを行うには、@JsonTest を使用しない場合、@Before メソッドでヘルパーの initFields メソッドを呼び出します。

Spring Boot の AssertJ ベースのヘルパーを使用して特定の JSON パスの数値をアサートする場合、型によっては isEqualTo を使用できない場合があります。代わりに、AssertJ の satisfies を使用して、値が指定された条件に一致することを表明できます。たとえば、次の例では、実際の数値が 0.01 のオフセット内の 0.15 に近い浮動小数点値であると主張しています。

	@Test
	void someTest() throws Exception {
		SomeObject value = new SomeObject(0.152f);
		assertThat(this.json.write(value)).extractingJsonPathNumberValue("@.test.numberValue")
			.satisfies((number) -> assertThat(number.floatValue()).isCloseTo(0.15f, within(0.01f)));
	}

自動構成された Spring MVC テスト

Spring MVC コントローラーが期待どおりに機能しているかどうかをテストするには、@WebMvcTest アノテーションを使用します。@WebMvcTest は、Spring MVC インフラストラクチャを自動構成し、スキャンされた Bean を @Controller@ControllerAdvice@JsonComponentConverterGenericConverterFilterHandlerInterceptorWebMvcConfigurerWebMvcRegistrationsHandlerMethodArgumentResolver に制限します。@WebMvcTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。

@WebMvcTest によって有効になる自動構成設定のリストは、付録にあります
Jackson Module などの追加コンポーネントを登録する必要がある場合は、テストで @Import を使用して追加の構成クラスをインポートできます。

多くの場合、@WebMvcTest は単一のコントローラーに限定され、@MockBean と組み合わせて使用され、必要なコラボレーターにモック実装を提供します。

@WebMvcTest は MockMvc も自動構成します。Mock MVC は、完全な HTTP サーバーを起動する必要なく、MVC コントローラーをすばやくテストする強力な方法を提供します。

@AutoConfigureMockMvc でアノテーションを付けることにより、非 @WebMvcTest (@SpringBootTest など)で MockMvc を自動構成することもできます。次の例では、MockMvc を使用しています。
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.docs.features.testing.springbootapplications.springmvctests.UserVehicleController;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(UserVehicleController.class)
class MyControllerTests {

	@Autowired
	private MockMvc mvc;

	@MockBean
	private UserVehicleService userVehicleService;

	@Test
	void testExample() throws Exception {
		given(this.userVehicleService.getVehicleDetails("sboot"))
			.willReturn(new VehicleDetails("Honda", "Civic"));
		this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
			.andExpect(status().isOk())
			.andExpect(content().string("Honda Civic"));
	}

}
自動構成の要素を構成する必要がある場合(たとえば、サーブレットフィルターを適用する必要がある場合)、@AutoConfigureMockMvc アノテーションの属性を使用できます。

HtmlUnit および Selenium を使用する場合、自動構成は HtmlUnit WebClient Bean および / または Selenium WebDriver Bean も提供します。次の例では、HtmlUnit を使用しています。

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.docs.features.testing.springbootapplications.springmvctests.UserVehicleController;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;

@WebMvcTest(UserVehicleController.class)
class MyHtmlUnitTests {

	@Autowired
	private WebClient webClient;

	@MockBean
	private UserVehicleService userVehicleService;

	@Test
	void testExample() throws Exception {
		given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic"));
		HtmlPage page = this.webClient.getPage("/sboot/vehicle.html");
		assertThat(page.getBody().getTextContent()).isEqualTo("Honda Civic");
	}

}
デフォルトでは、Spring Boot は WebDriver Bean を特別な「スコープ」に配置して、各テストの後にドライバーが終了し、新しいインスタンスが注入されるようにします。この動作を望まない場合は、@Scope("singleton") を WebDriver@Bean 定義に追加できます。
Spring Boot によって作成された webDriver スコープは、同じ名前のユーザー定義スコープを置き換えます。独自の webDriver スコープを定義すると、@WebMvcTest を使用すると動作が停止する場合があります。

クラスパスに Spring Security がある場合、@WebMvcTest は WebSecurityConfigurer Bean もスキャンします。そのようなテストのセキュリティを完全に無効にする代わりに、Spring Security のテストサポートを使用できます。Spring Security の MockMvc サポートの使用方法の詳細については、この Spring Security を使用したテスト 使い方セクションを参照してください。

Spring MVC テストを作成するだけでは不十分な場合があります。Spring Boot は、実際のサーバーで完全なエンドツーエンドテストを実行できます。

自動構成された Spring WebFlux テスト

Spring WebFlux コントローラーが期待どおりに機能していることをテストするには、@WebFluxTest アノテーションを使用できます。@WebFluxTest は、Spring WebFlux インフラストラクチャを自動構成し、スキャンされた Bean を @Controller@ControllerAdvice@JsonComponentConverterGenericConverterWebFilterWebFluxConfigurer に制限します。@WebFluxTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。

@WebFluxTest によって有効になる自動構成のリストは付録に記載されています。
Jackson Module などの追加コンポーネントを登録する必要がある場合は、テストで @Import を使用して追加の構成クラスをインポートできます。

多くの場合、@WebFluxTest は単一のコントローラーに限定され、@MockBean アノテーションと組み合わせて使用され、必要なコラボレーターにモック実装を提供します。

@WebFluxTest は WebTestClient も自動構成します。これにより、完全な HTTP サーバーを起動する必要なく、WebFlux コントローラーを迅速にテストする強力な方法が提供されます。

@AutoConfigureWebTestClient でアノテーションを付けることにより、非 @WebFluxTest (@SpringBootTest など)で WebTestClient を自動構成することもできます。次の例は、@WebFluxTest と WebTestClient の両方を使用するクラスを示しています。
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.docs.features.testing.springbootapplications.springwebfluxtests.UserVehicleController;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;

import static org.mockito.BDDMockito.given;

@WebFluxTest(UserVehicleController.class)
class MyControllerTests {

	@Autowired
	private WebTestClient webClient;

	@MockBean
	private UserVehicleService userVehicleService;

	@Test
	void testExample() {
		given(this.userVehicleService.getVehicleDetails("sboot"))
			.willReturn(new VehicleDetails("Honda", "Civic"));
		this.webClient.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN).exchange()
			.expectStatus().isOk()
			.expectBody(String.class).isEqualTo("Honda Civic");
	}

}
モック Web アプリケーションで WebTestClient を使用するのは、現時点では WebFlux でのみ機能するため、このセットアップは WebFlux アプリケーションでのみサポートされます。
@WebFluxTest は、機能する Web フレームワークを介して登録されたルートを検出できません。コンテキストで RouterFunction Bean をテストするには、@Import または @SpringBootTest を使用して RouterFunction を自分でインポートすることを検討してください。
@WebFluxTest は、型 SecurityWebFilterChain の @Bean として登録されているカスタムセキュリティ構成を検出できません。これをテストに含めるには、@Import または @SpringBootTest を使用して、Bean を登録する構成をインポートする必要があります。
Spring WebFlux テストを書くだけでは十分でない場合があります。Spring Boot は、実際のサーバーで完全なエンドツーエンドテストを実行するのに役立ちます。

自動構成された Spring GraphQL テスト

Spring GraphQL は、専用のテストサポートモジュールを提供します。プロジェクトに追加する必要があります。

<dependencies>
	<dependency>
		<groupId>org.springframework.graphql</groupId>
		<artifactId>spring-graphql-test</artifactId>
		<scope>test</scope>
	</dependency>
	<!-- Unless already present in the compile scope -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-webflux</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>
dependencies {
	testImplementation("org.springframework.graphql:spring-graphql-test")
	// Unless already present in the implementation configuration
	testImplementation("org.springframework.boot:spring-boot-starter-webflux")
}

このテストモジュールは GraphQlTester を提供します。テスターはテストで頻繁に使用されるため、必ず使用に慣れてください。GraphQlTester バリアントがあり、Spring Boot はテストの型に応じて自動構成します。

  • ExecutionGraphQlServiceTester は、クライアントもトランスポートも使用せずに、サーバー側でテストを実行します

  • HttpGraphQlTester は、ライブサーバーの有無にかかわらず、サーバーに接続するクライアントでテストを実行します

Spring Boot は、@GraphQlTest アノテーションを使用して Spring GraphQL コントローラーをテストできます。@GraphQlTest は、トランスポートやサーバーを使用せずに、Spring GraphQL インフラストラクチャを自動構成します。これにより、スキャンされた Bean が @ControllerRuntimeWiringConfigurerJsonComponentConverterGenericConverterDataFetcherExceptionResolverInstrumentationGraphQlSourceBuilderCustomizer に制限されます。@GraphQlTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。

@GraphQlTest によって有効になる自動構成のリストは付録に記載されています。

多くの場合、@GraphQlTest は一連のコントローラーに限定され、@MockBean アノテーションと組み合わせて使用され、必要なコラボレーターにモック実装を提供します。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.docs.web.graphql.runtimewiring.GreetingController;
import org.springframework.boot.test.autoconfigure.graphql.GraphQlTest;
import org.springframework.graphql.test.tester.GraphQlTester;

@GraphQlTest(GreetingController.class)
class GreetingControllerTests {

	@Autowired
	private GraphQlTester graphQlTester;

	@Test
	void shouldGreetWithSpecificName() {
		this.graphQlTester.document("{ greeting(name: \"Alice\") } ")
			.execute()
			.path("greeting")
			.entity(String.class)
			.isEqualTo("Hello, Alice!");
	}

	@Test
	void shouldGreetWithDefaultName() {
		this.graphQlTester.document("{ greeting } ")
			.execute()
			.path("greeting")
			.entity(String.class)
			.isEqualTo("Hello, Spring!");
	}

}

@SpringBootTest テストは完全な統合テストであり、アプリケーション全体が関与します。ランダムポートまたは定義済みポートを使用する場合、ライブサーバーが構成され、HttpGraphQlTester Bean が自動的に提供されるため、サーバーのテストに使用できます。MOCK 環境が構成されている場合、テストクラスに @AutoConfigureHttpGraphQlTester アノテーションを付けることで、HttpGraphQlTester Bean をリクエストすることもできます。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureHttpGraphQlTester;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.graphql.test.tester.HttpGraphQlTester;

@AutoConfigureHttpGraphQlTester
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class GraphQlIntegrationTests {

	@Test
	void shouldGreetWithSpecificName(@Autowired HttpGraphQlTester graphQlTester) {
		HttpGraphQlTester authenticatedTester = graphQlTester.mutate()
			.webTestClient((client) -> client.defaultHeaders((headers) -> headers.setBasicAuth("admin", "ilovespring")))
			.build();
		authenticatedTester.document("{ greeting(name: \"Alice\") } ")
			.execute()
			.path("greeting")
			.entity(String.class)
			.isEqualTo("Hello, Alice!");
	}

}

自動構成された Data Cassandra テスト

@DataCassandraTest を使用して、Cassandra アプリケーションをテストできます。デフォルトでは、CassandraTemplate を構成し、@Table クラスをスキャンし、Spring Data Cassandra リポジトリを構成します。@DataCassandraTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。(Spring Boot で Cassandra を使用する方法の詳細については、"Cassandra" を参照してください。)

@DataCassandraTest によって有効になる自動構成設定のリストは、付録にあります

次の例は、Spring Boot で Cassandra テストを使用するための一般的なセットアップを示しています。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.cassandra.DataCassandraTest;

@DataCassandraTest
class MyDataCassandraTests {

	@Autowired
	private SomeRepository repository;

}

自動構成された Data Couchbase テスト

@DataCouchbaseTest を使用して Couchbase アプリケーションをテストできます。デフォルトでは、CouchbaseTemplate または ReactiveCouchbaseTemplate を構成し、@Document クラスをスキャンし、Spring Data Couchbase リポジトリを構成します。@DataCouchbaseTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。(Couchbase を Spring Boot とともに使用する方法の詳細については、この章で前述した "Couchbase" を参照してください。)

@DataCouchbaseTest によって有効になる自動構成設定のリストは、付録にあります

次の例は、Spring Boot で Couchbase テストを使用するための一般的なセットアップを示しています。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.couchbase.DataCouchbaseTest;

@DataCouchbaseTest
class MyDataCouchbaseTests {

	@Autowired
	private SomeRepository repository;

	// ...

}

自動構成された Data Elasticsearch テスト

@DataElasticsearchTest を使用して Elasticsearch アプリケーションをテストできます。デフォルトでは、ElasticsearchRestTemplate を構成し、@Document クラスをスキャンし、Spring Data Elasticsearch リポジトリを構成します。@DataElasticsearchTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。(Elasticsearch を Spring Boot で使用する方法の詳細については、この章で前述した "Elasticsearch" を参照してください。)

@DataElasticsearchTest によって有効になる自動構成設定のリストは、付録にあります

次の例は、Spring Boot で Elasticsearch テストを使用するための一般的なセットアップを示しています。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.elasticsearch.DataElasticsearchTest;

@DataElasticsearchTest
class MyDataElasticsearchTests {

	@Autowired
	private SomeRepository repository;

	// ...

}

自動構成された Data JPA テスト

@DataJpaTest アノテーションを使用して JPA アプリケーションをテストできます。デフォルトでは、@Entity クラスをスキャンし、Spring Data JPA リポジトリを構成します。組み込みデータベースがクラスパスで使用可能な場合は、それも構成します。SQL クエリは、spring.jpa.show-sql プロパティを true に設定することにより、デフォルトでログに記録されます。これは、アノテーションの showSql 属性を使用して無効にできます。

@DataJpaTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。

@DataJpaTest によって有効になる自動構成設定のリストは、付録にあります

デフォルトでは、Data JPA テストはトランザクションであり、各テストの終了時にロールバックされます。詳細については、Spring Framework リファレンスドキュメントの関連セクションを参照してください。それが望んでいない場合、次のようにテストまたはクラス全体のトランザクション管理を無効にできます。

import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@DataJpaTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
class MyNonTransactionalTests {

	// ...

}

Data JPA テストでは、TestEntityManager (Javadoc) Bean を挿入することもできます。これは、テスト用に特別に設計された標準の JPA EntityManager の代替手段を提供します。

TestEntityManager は、@AutoConfigureTestEntityManager を追加することにより、Spring ベースのテストクラスのいずれかに自動構成することもできます。その際、テストクラスまたはメソッドに @Transactional を追加するなどして、テストがトランザクションで実行されていることを確認してください。

必要に応じて、JdbcTemplate も利用できます。次の例は、使用中の @DataJpaTest アノテーションを示しています。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class MyRepositoryTests {

	@Autowired
	private TestEntityManager entityManager;

	@Autowired
	private UserRepository repository;

	@Test
	void testExample() {
		this.entityManager.persist(new User("sboot", "1234"));
		User user = this.repository.findByUsername("sboot");
		assertThat(user.getUsername()).isEqualTo("sboot");
		assertThat(user.getEmployeeNumber()).isEqualTo("1234");
	}

}

メモリ内の組み込みデータベースは、高速でインストールを必要としないため、一般にテストに適しています。ただし、次の例に示すように、実際のデータベースに対してテストを実行する場合は、@AutoConfigureTestDatabase アノテーションを使用できます。

import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
class MyRepositoryTests {

	// ...

}

自動構成された JDBC テスト

@JdbcTest は @DataJpaTest に似ていますが、DataSource のみを必要とし、Spring Data JDBC を使用しないテスト用です。デフォルトでは、メモリ内埋め込みデータベースと JdbcTemplate を構成します。@JdbcTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties を使用して、@ConfigurationProperties Bean を含めることができます。

@JdbcTest によって有効になる自動構成のリストは付録に記載されています。

デフォルトでは、JDBC テストはトランザクション対応であり、各テストの終わりにロールバックします。詳細については、Spring Framework リファレンスドキュメントの関連セクションを参照してください。それが望んでいない場合は、次のように、テストまたはクラス全体のトランザクション管理を無効にできます。

import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@JdbcTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
class MyTransactionalTests {

}

テストを実際のデータベースに対して実行したい場合は、@DataJpaTest と同じ方法で @AutoConfigureTestDatabase アノテーションを使用できます。( "自動構成された Data JPA テスト" を参照してください。)

自動構成された Data JDBC テスト

@DataJdbcTest は @JdbcTest に似ていますが、Spring Data JDBC リポジトリを使用するテスト用です。デフォルトでは、インメモリ組み込みデータベース、JdbcTemplate、Spring Data JDBC リポジトリが構成されます。@DataJdbcTest アノテーションが使用されている場合、AbstractJdbcConfiguration サブクラスのみがスキャンされ、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties を使用して、@ConfigurationProperties Bean を組み込むことができます。

@DataJdbcTest によって有効になる自動構成のリストは付録に記載されています。

デフォルトでは、Data JDBC テストはトランザクションであり、各テストの終了時にロールバックされます。詳細については、Spring Framework リファレンスドキュメントの関連セクションを参照してください。それが望んでいない場合、JDBC の例に示すように、テストまたはテストクラス全体のトランザクション管理を無効にすることができます。

テストを実際のデータベースに対して実行したい場合は、@DataJpaTest と同じ方法で @AutoConfigureTestDatabase アノテーションを使用できます。( "自動構成された Data JPA テスト" を参照してください。)

自動構成された Data R2DBC テスト

@DataR2dbcTest は @DataJdbcTest に似ていますが、Spring Data R2DBC リポジトリを使用するテスト用です。デフォルトでは、インメモリ組み込みデータベース、R2dbcEntityTemplate、Spring Data R2DBC リポジトリが構成されます。@DataR2dbcTest アノテーションが使用されている場合、通常の @Component Bean および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties を使用して、@ConfigurationProperties Bean を含めることができます。

@DataR2dbcTest によって有効になる自動構成のリストは付録に記載されています。

デフォルトでは、データ R2DBC テストはトランザクションではありません。

テストを実際のデータベースに対して実行したい場合は、@DataJpaTest と同じ方法で @AutoConfigureTestDatabase アノテーションを使用できます。( "自動構成された Data JPA テスト" を参照してください。)

自動構成された jOOQ テスト

@JooqTest は、@JdbcTest と同様の方法で使用できますが、jOOQ 関連のテストに使用できます。jOOQ はデータベーススキーマに対応する Java ベースのスキーマに大きく依存しているため、既存の DataSource が使用されます。インメモリデータベースに置き換える場合は、@AutoConfigureTestDatabase を使用してこれらの設定を上書きできます。(Spring Boot での jOOQ の使用の詳細については、"jOOQ を使用する" を参照してください) @JooqTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。

@JooqTest によって有効になる自動構成のリストは付録に記載されています。

@JooqTest は DSLContext を構成します。次の例は、使用中の @JooqTest アノテーションを示しています。

import org.jooq.DSLContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jooq.JooqTest;

@JooqTest
class MyJooqTests {

	@Autowired
	private DSLContext dslContext;

	// ...

}

JOOQ テストはトランザクション対応であり、デフォルトでは各テストの終わりにロールバックします。それが望んでいない場合、JDBC の例に示すように、テストまたはテストクラス全体のトランザクション管理を無効にすることができます。

自動構成された Data MongoDB テスト

@DataMongoTest を使用して MongoDB アプリケーションをテストできます。デフォルトでは、MongoTemplate を構成し、@Document クラスをスキャンし、Spring Data MongoDB リポジトリを構成します。@DataMongoTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。(Spring Boot での MongoDB の使用の詳細については、"MongoDB" を参照してください。)

@DataMongoTest によって有効になる自動構成設定のリストは、付録にあります

次のクラスは、使用中の @DataMongoTest アノテーションを示しています。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.data.mongodb.core.MongoTemplate;

@DataMongoTest
class MyDataMongoDbTests {

	@Autowired
	private MongoTemplate mongoTemplate;

	// ...

}

自動構成された Data Neo4j テスト

@DataNeo4jTest を使用して Neo4j アプリケーションをテストできます。デフォルトでは、@Node クラスをスキャンし、Spring Data Neo4j リポジトリを構成します。@DataNeo4jTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties は、@ConfigurationProperties Bean を含めるために使用できます。(Spring Boot での Neo4J の使用の詳細については、"Neo4j" を参照してください。)

@DataNeo4jTest によって有効になる自動構成設定のリストは、付録にあります

次の例は、Spring Boot で Neo4J テストを使用するための一般的なセットアップを示しています。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest;

@DataNeo4jTest
class MyDataNeo4jTests {

	@Autowired
	private SomeRepository repository;

	// ...

}

デフォルトでは、Data Neo4j テストはトランザクション対応であり、各テストの終わりにロールバックします。詳細については、Spring Framework リファレンスドキュメントの関連セクションを参照してください。それが望んでいない場合は、次のように、テストまたはクラス全体のトランザクション管理を無効にできます。

import org.springframework.boot.test.autoconfigure.data.neo4j.DataNeo4jTest;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@DataNeo4jTest
@Transactional(propagation = Propagation.NOT_SUPPORTED)
class MyDataNeo4jTests {

}
トランザクションテストは、リアクティブアクセスではサポートされていません。このスタイルを使用している場合は、上記のように @DataNeo4jTest テストを構成する必要があります。

自動構成された Data Redis テスト

@DataRedisTest を使用して Redis アプリケーションをテストできます。デフォルトでは、@RedisHash クラスをスキャンし、Spring Data Redis リポジトリを構成します。@DataRedisTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties を使用して、@ConfigurationProperties Bean を含めることができます。(Spring Boot で Redis を使用する方法の詳細については、"Redis" を参照してください。)

@DataRedisTest によって有効になる自動構成設定のリストは、付録にあります

次の例は、使用中の @DataRedisTest アノテーションを示しています。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.redis.DataRedisTest;

@DataRedisTest
class MyDataRedisTests {

	@Autowired
	private SomeRepository repository;

	// ...

}

自動構成された Data LDAP テスト

@DataLdapTest を使用して LDAP アプリケーションをテストできます。デフォルトでは、インメモリ組み込み LDAP(使用可能な場合)を構成し、LdapTemplate を構成し、@Entry クラスをスキャンし、Spring Data LDAP リポジトリを構成します。@DataLdapTest アノテーションが使用されている場合、通常の @Component および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties を使用して、@ConfigurationProperties Bean を含めることができます。(Spring Boot での LDAP の使用の詳細については、"LDAP" を参照してください。)

@DataLdapTest によって有効になる自動構成設定のリストは、付録にあります

次の例は、使用中の @DataLdapTest アノテーションを示しています。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest;
import org.springframework.ldap.core.LdapTemplate;

@DataLdapTest
class MyDataLdapTests {

	@Autowired
	private LdapTemplate ldapTemplate;

	// ...

}

メモリ内の組み込み LDAP は、高速であり、開発者がインストールする必要がないため、一般にテストに適しています。ただし、実際の LDAP サーバーに対してテストを実行する場合は、次の例に示すように、組み込みの LDAP 自動構成を除外する必要があります。

import org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration;
import org.springframework.boot.test.autoconfigure.data.ldap.DataLdapTest;

@DataLdapTest(excludeAutoConfiguration = EmbeddedLdapAutoConfiguration.class)
class MyDataLdapTests {

	// ...

}

自動構成された REST クライアント

@RestClientTest アノテーションを使用して、REST クライアントをテストできます。デフォルトでは、Jackson、GSON、Jsonb のサポートが自動構成され、RestTemplateBuilder および RestClient.Builder が構成され、MockRestServiceServer のサポートが追加されます。@RestClientTest アノテーションが使用されている場合、通常の @Component Bean および @ConfigurationProperties Bean はスキャンされません。@EnableConfigurationProperties を使用して、@ConfigurationProperties Bean を含めることができます。

@RestClientTest によって有効になる自動構成設定のリストは、付録にあります

テストする特定の Bean は、@RestClientTest の value または components 属性を使用して指定する必要があります。

テスト対象の Bean で RestTemplateBuilder を使用し、RestTemplate の構築時に RestTemplateBuilder.rootUri(String rootUri) が呼び出された場合、次の例に示すように、ルート URI を MockRestServiceServer の期待値から省略する必要があります。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

@RestClientTest(org.springframework.boot.docs.testing.springbootapplications.autoconfiguredrestclient.RemoteVehicleDetailsService.class)
class MyRestTemplateServiceTests {

	@Autowired
	private RemoteVehicleDetailsService service;

	@Autowired
	private MockRestServiceServer server;

	@Test
	void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() {
		this.server.expect(requestTo("/greet/details")).andRespond(withSuccess("hello", MediaType.TEXT_PLAIN));
		String greeting = this.service.callRestService();
		assertThat(greeting).isEqualTo("hello");
	}

}

テスト対象の Bean で RestClient.Builder を使用する場合、または rootUri(String rootURI) を呼び出さずに RestTemplateBuilder を使用する場合、次の例に示すように、完全な URI を MockRestServiceServer の期待値で使用する必要があります。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;

@RestClientTest(RemoteVehicleDetailsService.class)
class MyRestClientServiceTests {

	@Autowired
	private RemoteVehicleDetailsService service;

	@Autowired
	private MockRestServiceServer server;

	@Test
	void getVehicleDetailsWhenResultIsSuccessShouldReturnDetails() {
		this.server.expect(requestTo("https://example.com/greet/details"))
			.andRespond(withSuccess("hello", MediaType.TEXT_PLAIN));
		String greeting = this.service.callRestService();
		assertThat(greeting).isEqualTo("hello");
	}

}

自動構成された Spring REST Docs テスト

@AutoConfigureRestDocs アノテーションを使用して、Mock MVC、REST Assured、または WebTestClient を使用したテストで Spring REST Docs を使用できます。Spring REST Docs の JUnit 拡張機能の必要性がなくなります。

@AutoConfigureRestDocs を使用して、デフォルトの出力ディレクトリをオーバーライドできます(Maven を使用している場合は target/generated-snippets、Gradle を使用している場合は build/generated-snippets)。また、ドキュメント化された URI に表示されるホスト、スキーム、ポートの構成にも使用できます。

モック MVC を使用した自動構成 Spring REST Docs テスト

@AutoConfigureRestDocs は、サーブレットベースの Web アプリケーションをテストするときに Spring REST Docs を使用するように MockMvc Bean をカスタマイズします。次の例に示すように、@Autowired を使用して注入し、モック MVC と Spring REST Docs を使用する場合と同じようにテストで使用できます。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(UserController.class)
@AutoConfigureRestDocs
class MyUserDocumentationTests {

	@Autowired
	private MockMvc mvc;

	@Test
	void listUsers() throws Exception {
		this.mvc.perform(get("/users").accept(MediaType.TEXT_PLAIN))
			.andExpect(status().isOk())
			.andDo(document("list-users"));
	}

}

@AutoConfigureRestDocs の属性で提供されるよりも Spring REST Docs 構成をより詳細に制御する必要がある場合は、次の例に示すように、RestDocsMockMvcConfigurationCustomizer Bean を使用できます。

import org.springframework.boot.test.autoconfigure.restdocs.RestDocsMockMvcConfigurationCustomizer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationConfigurer;
import org.springframework.restdocs.templates.TemplateFormats;

@TestConfiguration(proxyBeanMethods = false)
public class MyRestDocsConfiguration implements RestDocsMockMvcConfigurationCustomizer {

	@Override
	public void customize(MockMvcRestDocumentationConfigurer configurer) {
		configurer.snippets().withTemplateFormat(TemplateFormats.markdown());
	}

}

パラメーター化された出力ディレクトリの Spring REST Docs サポートを利用する場合は、RestDocumentationResultHandler Bean を作成できます。自動構成は、この結果ハンドラーを使用して alwaysDo を呼び出します。これにより、各 MockMvc 呼び出しでデフォルトのスニペットが自動的に生成されます。次の例は、定義されている RestDocumentationResultHandler を示しています。

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.restdocs.mockmvc.RestDocumentationResultHandler;

@TestConfiguration(proxyBeanMethods = false)
public class MyResultHandlerConfiguration {

	@Bean
	public RestDocumentationResultHandler restDocumentation() {
		return MockMvcRestDocumentation.document("{method-name}");
	}

}

WebTestClient を使用した自動構成 Spring REST Docs テスト

@AutoConfigureRestDocs は、リアクティブ Web アプリケーションをテストするときに WebTestClient と共に使用することもできます。次の例に示すように、@Autowired を使用して注入し、@WebFluxTest および Spring REST Docs を使用する場合と同じようにテストで使用できます。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.test.web.reactive.server.WebTestClient;

import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document;

@WebFluxTest
@AutoConfigureRestDocs
class MyUsersDocumentationTests {

	@Autowired
	private WebTestClient webTestClient;

	@Test
	void listUsers() {
		this.webTestClient
			.get().uri("/")
		.exchange()
		.expectStatus()
			.isOk()
		.expectBody()
			.consumeWith(document("list-users"));
	}

}

@AutoConfigureRestDocs の属性で提供されるよりも Spring REST Docs 構成をより詳細に制御する必要がある場合は、次の例に示すように、RestDocsWebTestClientConfigurationCustomizer Bean を使用できます。

import org.springframework.boot.test.autoconfigure.restdocs.RestDocsWebTestClientConfigurationCustomizer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.restdocs.webtestclient.WebTestClientRestDocumentationConfigurer;

@TestConfiguration(proxyBeanMethods = false)
public class MyRestDocsConfiguration implements RestDocsWebTestClientConfigurationCustomizer {

	@Override
	public void customize(WebTestClientRestDocumentationConfigurer configurer) {
		configurer.snippets().withEncoding("UTF-8");
	}

}

パラメーター化された出力ディレクトリに対して Spring REST Docs サポートを利用する場合は、WebTestClientBuilderCustomizer を使用して、すべてのエンティティ交換結果のコンシューマーを構成できます。次の例は、そのような WebTestClientBuilderCustomizer が定義されていることを示しています。

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.reactive.server.WebTestClientBuilderCustomizer;
import org.springframework.context.annotation.Bean;

import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document;

@TestConfiguration(proxyBeanMethods = false)
public class MyWebTestClientBuilderCustomizerConfiguration {

	@Bean
	public WebTestClientBuilderCustomizer restDocumentation() {
		return (builder) -> builder.entityExchangeResultConsumer(document("{method-name}"));
	}

}

REST が保証された自動構成 Spring REST Docs テスト

@AutoConfigureRestDocs は、Spring REST Docs を使用するように事前構成された RequestSpecification Bean をテストで使用できるようにします。次の例に示すように、REST Assured および Spring REST Docs を使用する場合と同様に、@Autowired を使用して注入し、テストで使用できます。

import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.server.LocalServerPort;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.is;
import static org.springframework.restdocs.restassured.RestAssuredRestDocumentation.document;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureRestDocs
class MyUserDocumentationTests {

	@Test
	void listUsers(@Autowired RequestSpecification documentationSpec, @LocalServerPort int port) {
		given(documentationSpec)
			.filter(document("list-users"))
		.when()
			.port(port)
			.get("/")
		.then().assertThat()
			.statusCode(is(200));
	}

}

@AutoConfigureRestDocs の属性で提供されるよりも Spring REST Docs 構成をより詳細に制御する必要がある場合、次の例に示すように、RestDocsRestAssuredConfigurationCustomizer Bean を使用できます。

import org.springframework.boot.test.autoconfigure.restdocs.RestDocsRestAssuredConfigurationCustomizer;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.restdocs.restassured.RestAssuredRestDocumentationConfigurer;
import org.springframework.restdocs.templates.TemplateFormats;

@TestConfiguration(proxyBeanMethods = false)
public class MyRestDocsConfiguration implements RestDocsRestAssuredConfigurationCustomizer {

	@Override
	public void customize(RestAssuredRestDocumentationConfigurer configurer) {
		configurer.snippets().withTemplateFormat(TemplateFormats.markdown());
	}

}

自動構成された Spring Web Services テスト

自動構成された Spring Web Services クライアントテスト

@WebServiceClientTest を使用して、Spring Web Services プロジェクトを使用して Web サービスを呼び出すアプリケーションをテストできます。デフォルトでは、モック WebServiceServer Bean を構成し、WebServiceTemplateBuilder を自動的にカスタマイズします。(Spring Boot での Web サービスの使用の詳細については、"Web サービス" を参照してください。)

@WebServiceClientTest によって有効になる自動構成設定のリストは、付録にあります

次の例は、使用中の @WebServiceClientTest アノテーションを示しています。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.webservices.client.WebServiceClientTest;
import org.springframework.ws.test.client.MockWebServiceServer;
import org.springframework.xml.transform.StringSource;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.ws.test.client.RequestMatchers.payload;
import static org.springframework.ws.test.client.ResponseCreators.withPayload;

@WebServiceClientTest(SomeWebService.class)
class MyWebServiceClientTests {

	@Autowired
	private MockWebServiceServer server;

	@Autowired
	private SomeWebService someWebService;

	@Test
	void mockServerCall() {
		this.server
			.expect(payload(new StringSource("<request/>")))
			.andRespond(withPayload(new StringSource("<response><status>200</status></response>")));
		assertThat(this.someWebService.test())
			.extracting(Response::getStatus)
			.isEqualTo(200);
	}

}

自動構成された Spring Web Services サーバーテスト

@WebServiceServerTest を使用して、Spring Web Services プロジェクトを使用して Web サービスを実装するアプリケーションをテストできます。デフォルトでは、Web サービスエンドポイントの呼び出しに使用できる MockWebServiceClient Bean を構成します。(Spring Boot での Web サービスの使用の詳細については、"Web サービス" を参照してください。)

@WebServiceServerTest によって有効になる自動構成設定のリストは、付録にあります

次の例は、使用中の @WebServiceServerTest アノテーションを示しています。

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.docs.features.testing.springbootapplications.autoconfiguredwebservices.server.ExampleEndpoint;
import org.springframework.boot.test.autoconfigure.webservices.server.WebServiceServerTest;
import org.springframework.ws.test.server.MockWebServiceClient;
import org.springframework.ws.test.server.RequestCreators;
import org.springframework.ws.test.server.ResponseMatchers;
import org.springframework.xml.transform.StringSource;

@WebServiceServerTest(ExampleEndpoint.class)
class MyWebServiceServerTests {

	@Autowired
	private MockWebServiceClient client;

	@Test
	void mockServerCall() {
		this.client
			.sendRequest(RequestCreators.withPayload(new StringSource("<ExampleRequest/>")))
			.andExpect(ResponseMatchers.payload(new StringSource("<ExampleResponse>42</ExampleResponse>")));
	}

}

追加の自動構成とスライス

各スライスは、スライスの一部として含まれるべき自動構成を定義する 1 つ以上の @AutoConfigure…​ アノテーションを提供します。次の例に示すように、カスタム @AutoConfigure…​ アノテーションを作成するか、@ImportAutoConfiguration をテストに追加することにより、テストごとに自動構成を追加できます。

import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration;
import org.springframework.boot.test.autoconfigure.jdbc.JdbcTest;

@JdbcTest
@ImportAutoConfiguration(IntegrationAutoConfiguration.class)
class MyJdbcTests {

}
自動構成は Spring Boot によって特定の方法で処理されるため、通常の @Import アノテーションを使用して自動構成をインポートしないようにしてください。

または、次の例に示すように、META-INF/spring に保存されているファイルにスライスアノテーションを登録することにより、スライスアノテーションを使用するための自動構成を追加できます。

META-INF/Spring/org.springframework.boot.test.autoconfigure.jdbc.JdbcTest.imports
com.example.IntegrationAutoConfiguration

この例では、@JdbcTest でアノテーションが付けられたすべてのテストで com.example.IntegrationAutoConfiguration が有効になっています。

このファイルでは、# でコメントを使用できます。
スライスまたは @AutoConfigure…​ アノテーションは、@ImportAutoConfiguration でメタアノテーションが付けられている限り、この方法でカスタマイズできます。

ユーザー設定とスライス

実用的な方法でコードを構造化すると、@SpringBootApplication クラスがテストの構成としてデフォルトで使用されます

その場合、アプリケーションのメインクラスに、その機能の特定の領域に固有の構成設定を散らかさないことが重要になります。

Spring Data MongoDB を使用しており、その自動構成に依存しており、監査を有効にしていると仮定します。@SpringBootApplication を次のように定義できます。

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.config.EnableMongoAuditing;

@SpringBootApplication
@EnableMongoAuditing
public class MyApplication {

	// ...

}

このクラスはテストのソース構成であるため、スライステストでは実際に Mongo 監査を有効にしようとしますが、これは明らかに意図したものではありません。推奨されるアプローチは、次の例に示すように、その領域固有の構成をアプリケーションと同じレベルの別の @Configuration クラスに移動することです。

import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.EnableMongoAuditing;

@Configuration(proxyBeanMethods = false)
@EnableMongoAuditing
public class MyMongoConfiguration {

	// ...

}
アプリケーションの複雑さに応じて、カスタマイズ用に 1 つの @Configuration クラスを使用することも、ドメイン領域ごとに 1 つのクラスを使用することもできます。後者のアプローチでは、必要に応じて、@Import アノテーションを使用してテストの 1 つでそれを有効にすることができます。スライステストで特定の @Configuration クラスを有効にする場合の詳細については、この使い方セクションを参照してください。

テストスライスは、@Configuration クラスをスキャンから除外します。例: @WebMvcTest の場合、次の構成では、テストスライスによってロードされたアプリケーションコンテキストに特定の WebMvcConfigurer Bean は含まれません。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration(proxyBeanMethods = false)
public class MyWebConfiguration {

	@Bean
	public WebMvcConfigurer testConfigurer() {
		return new WebMvcConfigurer() {
			// ...
		};
	}

}

ただし、以下の構成では、テストスライスによってカスタム WebMvcConfigurer がロードされます。

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class MyWebMvcConfigurer implements WebMvcConfigurer {

	// ...

}

混乱のもう 1 つの原因は、クラスパススキャンです。実用的な方法でコードを構造化しながら、追加のパッケージをスキャンする必要があると仮定します。アプリケーションは次のコードのようになります。

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({ "com.example.app", "com.example.another" })
public class MyApplication {

	// ...

}

そうすることで、デフォルトのコンポーネントスキャンディレクティブが効果的にオーバーライドされ、選択したスライスに関係なく、これら 2 つのパッケージがスキャンされるという副作用があります。たとえば、@DataJpaTest は、アプリケーションのコンポーネントとユーザー構成を突然スキャンするようです。繰り返しますが、カスタムディレクティブを別のクラスに移動することは、この課題を解決するための良い方法です。

これが選択肢ではない場合は、テストの階層のどこかに @SpringBootConfiguration を作成して、代わりに使用することができます。あるいは、テストのソースを指定して、デフォルトのソースを見つける動作を無効にすることもできます。

Spock を使用して Spring Boot アプリケーションをテストする

Spock 2.2 以降は、Spring Boot アプリケーションのテストに使用できます。これを行うには、Spock の spock-spring モジュールの -groovy-4.0 バージョンへの依存関係をアプリケーションのビルドに追加します。spock-spring は、Spring のテストフレームワークを Spock に統合します。詳細については、Spock の Spring モジュールのドキュメント (英語) を参照してください。