テスト: @SpringBootTest と @DataTest

spring_test ビルダーは、テストファイルのテストクラス、つまり @SpringBootTest() (spring_boot_starter_test のもの) または @DataTest() (spring_boot_starter_data のもの) を付けたクラスを読み、そのテストを package:test に登録する関数 runSpringTests() を書き出します。テストファイルの main がその関数を呼びます。

使う理由

package:test は、main から group と test で登録された関数だけを実行します。Spring では、JUnit がリフレクションでクラスの @Test メソッドを見つけ、Spring のテスト拡張が @Autowired フィールドに値を入れます。Dart には AOT モードの VM、Flutter、Web でリフレクションがないため、この作業はビルド時に行われます。ビルダーはクラスを読み、本来なら手で書く group、setUp、test の呼び出しを書き出します。

アノテーション自体は実行時に何もしません。その意味はすべて生成ファイルの中にあります。

入力と出力

ビルダーは、各ファイル test/<name>_test.dart に対して test/spring_gen/<name>.test.spring.dart を書き出します。test/ の下のパスは保たれます。

テストファイル 生成ファイル
test/checkout_test.dart test/spring_gen/checkout.test.spring.dart
test/orders/basket_test.dart test/spring_gen/orders/basket.test.spring.dart

生成ファイルは専用のフォルダーにあり、その名前は _test.dart で終わらないので、dart test がそれらをテストと見なすことはありません。

テキスト SpringBootTest も DataTest も含まないテストファイルや、それらのいずれかを付けたクラスを宣言しないテストファイルに対しては、ビルダーは何も書き出さず、何も言いません。test/ の外のファイルや、名前が _test.dart で終わらないファイルは読まれません。

最初のテスト

// test/shop_class_test.dart
import 'package:neon_books_server/src/catalog/catalog_service.dart';
import 'package:neon_books_server/src/shop/clock.dart';
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
import 'package:test/test.dart';

import 'spring_gen/shop_class.test.spring.dart'; // 生成

class FixedClock implements Clock {
  @override
  DateTime now() => DateTime.utc(2026, 10, 27, 12);
}

@SpringBootTest(properties: {'neon.shop.delivery-time': '3d'})
@ActiveProfiles(['dev', 'test'])
@TestEnvironment({'NEON_SHOP_NAME': 'Night Books'})
class ShopTest {
  // `clock` Bean を置き換える。
  @TestBean(type: Clock, name: 'clock')
  final clock = FixedClock();

  @Autowired()
  late MockMvc mvc;

  @Autowired()
  late Catalog catalog;

  @Value(r'${neon.shop.name}')
  late String shopName;

  @Test('properties from the annotation and the environment')
  void configuration() => expect(shopName, 'Night Books');

  @Test()
  @Tag('logs')
  void logsOfTheTest() => catalog.search('poetry', 0);

  @Nested('the catalog')
  final theCatalog = TheCatalog();
}

class TheCatalog {
  @Autowired()
  late Catalog catalog;

  @Test()
  void hasTheSampleBooks() => expect(catalog.search('', 0).total, 8);
}

void main() => runSpringTests();

ビルダーは次のように書き出します (server_guide サンプルの実際のファイルを短縮したもの)。

// test/spring_gen/shop_class.test.spring.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
// Generated by spring_core_dart_generator from the @SpringBootTest classes of shop_class_test.dart.

// ignore_for_file: type=lint, unused_import, unused_shown_name, duplicate_import

// テストファイルのインポートのコピー。
import 'package:neon_books_server/src/catalog/catalog_service.dart';
import 'package:neon_books_server/src/shop/clock.dart';
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
import 'package:test/test.dart';

// テストファイルそのもの。
import '../shop_class_test.dart';

import 'package:spring_boot_starter_test/generated.dart' as _sbt;

// springApplication を宣言する、アプリケーションの生成ファイル。
import '../../bin/spring_gen/main.spring.dart' as _app0;

/// Declares the tests of the `@SpringBootTest` classes of `shop_class_test.dart`.
void runSpringTests() {
  _sbt.group('ShopTest', () {
    final $instance = ShopTest();
    final $app = _sbt.springBootTest(
      _app0.springApplication,
      properties: {'neon.shop.delivery-time': '3d'},
      profiles: ['dev', 'test'],
      systemEnvironment: {'NEON_SHOP_NAME': 'Night Books'},
      overrides: [_sbt.BeanOverride<Clock>($instance.clock, name: 'clock')],
    );
    _sbt.setUp(() {
      $instance.mvc = $app.mockMvc;
      $instance.catalog = $app.getBean();
      $instance.shopName = $app.value(r'${neon.shop.name}');
    });
    _sbt.test(
      'properties from the annotation and the environment',
      () => $instance.configuration(),
    );
    _sbt.test(
      'logs of the test',
      () => $instance.logsOfTheTest(),
      tags: ['logs'],
    );
    _sbt.group('the catalog', () {
      _sbt.setUp(() {
        $instance.theCatalog.catalog = $app.getBean();
      });
      _sbt.test(
        'has the sample books',
        () => $instance.theCatalog.hasTheSampleBooks(),
      );
    });
  });
}

注目すべき点:

ビルダーの仕組み

  1. 軽いテキストチェック。 SpringBootTest も DataTest も含まないファイルはすぐにスキップされます。
  2. ファイルは解決されず、解析されます。 ビルダーはテストファイルを構文としてだけ読むので高速です。アノテーションは、インポートのプレフィックスの有無にかかわらず、単純な名前で認識されます (@Test() と @sbt.Test() は同じです)。
  3. アプリケーションが見つけられます。 ビルダーは bin/ と lib/ の .dart ファイル (生成ファイルを除く) から、@SpringBootApplication を付けたトップレベル関数を探します。どのアプリケーションが起動するか を参照してください。
  4. インポートがコピーされます。 生成ファイルは、同じプレフィックスと show / hide の指定子でテストファイルのすべてのインポートを繰り返し、テストファイル自身もインポートします。相対インポートは test/spring_gen/ からのパスに付け替えられます。そのため、アノテーションに書かれたすべての型と定数は、生成ファイルでも同じ意味になります。
  5. コードが書き出され、整形されます。 テストクラスごとに一つの group が、ファイル内の順に並びます。

構文だけでは情報が足りない二つの場合 (どちらも @TestBean フィールドに関するもの) にだけ、テストファイルはアナライザーで解決されます。

生成ファイルは package:spring_boot_starter_test/generated.dart を (_sbt として) インポートするので、テストパッケージには開発用の依存関係として spring_boot_starter_test が必要です。

main がすべきこと

テストファイルは生成ファイルをインポートし、main から runSpringTests() を呼ばなければなりません。

import 'spring_gen/checkout.test.spring.dart';

void main() => runSpringTests();

main は、この呼び出しの前後に他のテストを登録してもかまいません。インポートがない場合、ビルドは追加すべき行を示す警告をログに出します。

test/checkout_test.dart does not import 'spring_gen/checkout.test.spring.dart': add import 'spring_gen/checkout.test.spring.dart'; and void main() => runSpringTests();

生成ファイルはテストファイルをインポートし、テストファイルは生成ファイルをインポートします。Dart はライブラリ間のこのようなインポートの循環を許します。

どのアプリケーションが起動するか

springBootTest には springApplication ゲッターが必要で、メインのビルダーがそれをアプリケーションの main の .spring.dart に書き出します (アプリケーション: @SpringBootApplication を参照)。テストのビルダーは次のようにエントリーポイントを選びます。

状況 エントリーポイント
application: が与えられている そのファイル (パッケージ内のパス)。@SpringBootApplication 関数を宣言している限り、パッケージのどこにあってもかまいません (たとえば test/data_test/app/data_test_app.dart)
bin/ または lib/ に @SpringBootApplication 関数が一つ それ
ない ビルドエラー
複数 一つを指定するよう求めるビルドエラー

生成ファイルはアプリケーションの生成ファイルをインポートします。lib/ のエントリーポイントなら package:<package>/spring_gen/...、それ以外では相対パス (../../bin/spring_gen/main.spring.dart) です。メインのビルダーは test/ にも .spring.dart ファイルを生成するので、一つのグループのテストのために test/ の下で宣言した小さなアプリケーションも同じように動きます。

// bin/ に二つのアプリケーションがある: 起動するものを指定する。
@SpringBootTest(application: 'bin/admin.dart')
class AdminTest {
  // ...
}

@SpringBootTest のオプション

ビルダーは、各引数のソースを springBootTest の呼び出しにコピーします。書かれていないオプションは渡されず、springBootTest は自身のデフォルト (引数なし、リソースディレクトリとして test/resources、WebEnvironment.mock) を使います。

アノテーション springBootTest の引数
@SpringBootTest(args: [...]) args:
@SpringBootTest(properties: {...}) properties:
@TestPropertySource(properties: {...}) properties:。上のものとマージされる ({...a, ...b}、後のものが優先)
@TestPropertySource(locations: [...]) propertyFiles:
@SpringBootTest(resourceDirectories: [...]) resourceDirectories:
@SpringBootTest(webEnvironment: ...) webEnvironment:
@SpringBootTest(application: '...') どのアプリケーションが起動するか (上記を参照)
@ActiveProfiles([...]) profiles:
@TestEnvironment({...}) systemEnvironment:
static な @DynamicPropertySource メソッド dynamicProperties:
static な @ContextInitializer メソッド initializers:。それぞれ ApplicationContextInitializer.of(method) として
@TestBean フィールド overrides:。それぞれ BeanOverride として

@SpringBootTest、@DataTest、@ActiveProfiles、@TestPropertySource、@TestEnvironment、@Testcontainers はクラスに付けます。クラスごとにコンテキストは一つなので、メソッドに付けるとビルドが失敗します。

アノテーションの引数は、クラスの中で Dart が許すとおり、クラス名なしでテストクラスの static メンバーを指定できます。生成コードはクラスの外にあるので、ビルダーはクラス名を付け加えます (port に対して Fixtures.port)。

テストクラスのメンバー

注入されるフィールド

@Autowired()、@Value('...')、@LocalServerPort() のフィールドは、late で、final でも static でもなく、public で、型が書かれていなければなりません。

@Autowired()
late Checkout checkout;

フィールドが受け取る値は、宣言された型によって決まります。

フィールド 生成される代入
@LocalServerPort() late int port $app.localServerPort
@Value('${a.b}') late String x $app.value(...)。nullable な型では $app.optionalValue(...)
SpringBootTestContext テストコンテキストそのもの
MockMvc $app.mockMvc
ApplicationContext、ConfigurableApplicationContext $app.context
Environment、ConfigurableEnvironment $app.environment
List<T>、Iterable<T> $app.getBeans()
Set<T> $app.getBeans<T>().toSet()
Map<String, T> $app.context.getBeansOfType<T>()
ObjectProvider<T>、ObjectFactory<T>、Provider<T> $app.context.getBeanProvider()
その他の nullable な型 T? $app.findBean() (そのような Bean がなければ null)
その他の型 $app.getBean()

フィールドの @Qualifier('name') は、getBean、findBean、getBeans、getBeanProvider に qualifier: として渡されます。

@CapturedOutput() late CapturedLogs logs; フィールドは、テストのログレコードを受け取ります。グループは final $logs = _sbt.captureLogs(); で始まり、各テストの前にフィールドにそれが設定されます。

テストメソッドとライフサイクルメソッド

アノテーション 条件 生成されるもの
@Test() パラメーターのないインスタンスメソッド _sbt.test(name, () => $instance.method())
@BeforeEach() パラメーターのないインスタンスメソッド _sbt.setUp(...)
@AfterEach() パラメーターのないインスタンスメソッド _sbt.tearDown(...)
@BeforeAll() テストクラス (@Nested のものではない) の static メソッド _sbt.setUpAll(...)。コンテキストの起動前
@AfterAll() テストクラスの static メソッド _sbt.tearDownAll(...)。コンテキストが閉じた後

@BeforeAll メソッドは、クラスが生成される前に実行されるため static でなければなりません。@AfterAll メソッドの tearDownAll は springBootTest より前に登録され、package:test は tearDownAll のコールバックを逆順に実行するので、コンテキストが閉じた後に実行されます。

テストメソッドは Future を返してもかまいません。package:test はそれを待ちます。

テストやグループのオプション

アノテーション 付ける場所 生成されるもの
@DisplayName('...') @Test メソッド テストの名前
@Disabled() または @Disabled('why') クラス、@Test メソッド、@Nested フィールド skip: true または skip: 'why'
@Tag('slow') (繰り返し可) 同上 tags: [...]
@TestOptions(timeout:, retry:, testOn:, onPlatform:) 同上 test や group の同名の名前付き引数
@DirtiesContext() クラスまたは @Nested フィールド グループの各テストの後に新しいコンテキスト (_sbt.setUp($app.markDirty))
@DirtiesContext() @Test メソッド テストの開始時にコンテキストを dirty とし、次のテストが新しいものを受け取る

@Test メソッド (または @Nested フィールド) でないメンバーに付けると、これらのアノテーションは無視されるのではなく、ビルドを失敗させます。

入れ子のグループ

@Nested() を付けたフィールドは、クラスのグループの中のグループになります。その値は、同じテストファイルのクラスで生成されていなければなりません (final theCatalog = TheCatalog();)。入れ子のクラスは独自の @Autowired フィールド、テスト、@BeforeEach / @AfterEach メソッドを持ち、外側のクラスのコンテキストを共有します。その名前は @Nested('...') の引数、なければフィールド名を単語に分けたものです。

@TestBean、@Container、@BeforeAll、@AfterAll は外側のクラスに属します。入れ子のクラスに付けるとビルドが失敗します。

スーパークラス

テストクラスは、同じテストファイルで宣言されたクラスを継承できます。そのアノテーション付きのメンバーが、スーパークラスのものから順に含まれます。ファイルは構文として読まれるので、別のファイルで宣言されたスーパークラスは見えません。その場合、ビルドは警告をログに出します。

test/shop_test.dart: ShopTest extends BaseTest from another file; its @Test, @Autowired and other annotated members are not seen. Declare it in the test file.

@TestBean

@TestBean フィールドは、アプリケーションの Bean をフィールドの値で置き換えます。フィールドには値が必要で、生成されるオーバーライドは何が書かれているかによって決まります。

フィールド 生成されるオーバーライド
@TestBean() final PaymentGateway gateway = FakeGateway(); BeanOverride<PaymentGateway>($instance.gateway)
@TestBean(type: Clock, name: 'clock') final clock = FixedClock(); BeanOverride<Clock>($instance.clock, name: 'clock')
@TestBean(name: 'gateway') final gateway = FakeGateway(); BeanOverride.named(..., name: 'gateway', types: [...])。解決されたファイルから読んだ FakeGateway とそのスーパータイプの型を使う
@TestBean() final Mailer? mailer = ...; BeanOverride<Mailer>(...)。実行時に値が null なら、テストは @TestBean field ShopTest.mailer is null: it needs a value で失敗する

name: も type: も、書かれた型もない @TestBean() フィールドは、ビルドを失敗させます。ビルダーはそれがどの Bean を置き換えるのかわからないからです。

@DataTest

@DataTest() (spring_boot_starter_data のもの) は、アプリケーションのスライス、つまりインメモリーのデータベース上のデータ Bean を起動します。各テストはトランザクションの中で実行され、最後にロールバックされます。生成コードは package:spring_boot_starter_data/testing.dart をその URL で呼ぶので、spring_boot_starter_test とデータスターターは互いに依存しません。

// test/data_test/commit_test.dart
@DataTest(application: 'test/data_test/app/data_test_app.dart')
class CommitTest {
  @Autowired()
  late BookRepository books;

  @Test()
  @Commit()
  Future<void> commitsABook() async {
    await books.save(Book(title: 'Dune', year: 1965));
  }

  @Test()
  Future<void> startsEmptyAgain() async {
    expect(await books.count(), 0);
  }
}

void main() => runSpringTests();

生成されるもの (データスターターのテストから短縮):

import 'package:spring_boot_starter_test/generated.dart' as _sbt;
import 'package:spring_boot_starter_data/testing.dart' as _data;

import 'app/data_test_app.spring.dart' as _app0;

void runSpringTests() {
  _sbt.group('CommitTest', () {
    final $instance = CommitTest();
    // スライス: データ Bean だけを残すプロパティと初期化子。
    final $slice = _data.DataTestSetup(_app0.springApplication);
    final $app = _sbt.springBootTest(
      _app0.springApplication,
      properties: $slice.properties,
      initializers: [$slice.initializer],
    );
    _sbt.setUp(() {
      $instance.books = $app.getBean();
    });
    _sbt.test(
      'commits a book',
      () => _data.runInTestTransaction(
        $app.context,
        () => $instance.commitsABook(),
        rollback: false,
      ),
    );
    _sbt.test(
      'starts empty again',
      () => _data.runInTestTransaction(
        $app.context,
        () => $instance.startsEmptyAgain(),
      ),
    );
  });
}

@SpringBootTest との違い:

@DataTest の args:、properties:、resourceDirectories: は、@SpringBootTest と同じように渡されます。

コンテナー

@Container() を付けた static フィールドは、コンテナー (package:spring_boot_starter_test/containers.dart のもの) を保持します。コンテナーはクラスに対して一度、そのコンテキストより前に起動し、その後に取り除かれます。そのようなフィールドの @ServiceConnection() は、コンテナーの接続プロパティ (データベースなら spring.datasource.* など) をアプリケーションにも書き込みます。

@DataTest(
  application: 'test/data_test/postgres_app/postgres_data_app.dart',
  replaceDatabase: false,
)
@Testcontainers()
class ContainerPostgresTest {
  @Container()
  @ServiceConnection()
  static final postgres = PostgresContainer('postgres:17');

  @Autowired()
  late BookRepository books;

  @Test()
  Future<void> savesABook() async {
    await books.save(Book(title: 'Dune', year: 1965));
    expect(await books.count(), 1);
  }
}

生成されるもの (短縮):

_sbt.group('ContainerPostgresTest', () {
  // 最初に置く。@BeforeAll メソッドとコンテキストが、起動済みのコンテナーを見つけるように。
  final $containers = _sbt.TestContainers(
    {'ContainerPostgresTest.postgres': ContainerPostgresTest.postgres},
    serviceConnections: {'ContainerPostgresTest.postgres'},
  );
  _sbt.setUpAll($containers.start);
  _sbt.tearDownAll($containers.stop);
  final $instance = ContainerPostgresTest();
  final $slice = _data.DataTestSetup(
    _app0.springApplication,
    replaceDatabase: false,
  );
  final $app = _sbt.springBootTest(
    _app0.springApplication,
    properties: $slice.properties,
    // コンテナーの接続を先に。@DynamicPropertySource メソッドが
    // それを変更できるように。
    dynamicProperties: (registry) {
      $containers.registerConnections(registry);
    },
    initializers: [$slice.initializer],
  );
  // ...
}, skip: _sbt.TestContainers.skipReason());

@Container フィールドは、static で、public で、テストクラス (@Nested のものではない) にあり、値を持たなければなりません (または late)。同じフィールドに @Container なしで付けた @ServiceConnection はビルドを失敗させます。

ビルドエラー

ビルダーは、エラーの原因となるメンバーの位置で、path:line:column: message としてエラーを報告します。その一部:

問題 メッセージ (短縮)
アプリケーションがない No application in this package: @SpringBootTest needs a @SpringBootApplication entry point in bin/ or lib/.
複数のアプリケーション Several applications in this package (bin/a.dart, bin/b.dart): name one, @SpringBootTest(application: 'bin/a.dart').
application: がエントリーポイントを指していない 'bin/x.dart' is not an entry point with @SpringBootApplication of this package (...)
一つのクラスに両方のアノテーション @DataTest and @SpringBootTest on one class: ... keep one, or write a second class.
クラスを生成できない 'ShopTest' is private、is abstract、has no unnamed constructor、または needs a constructor without required parameters
注入フィールドが late でない、または final / static @Autowired field 'checkout' must be late and not final or static: @Autowired() late Checkout checkout;
型のない注入フィールド @Autowired field 'checkout' needs its type written.
パラメーターを持つテストメソッド @Test method pays has parameters: test methods take none (widget tests with a WidgetTester come with spring_boot_starter_flutter_test).
static でない @BeforeAll @BeforeAll method start must be static: it runs before the class is created.
@DataTest の外の @Commit や @Rollback @Commit needs a @DataTest class: only its tests run in a transaction.
アノテーション引数の中の private な名前 '_port' is private to the test file; the generated test cannot reach it: make it public.

生成コードは別のライブラリにあるので、private な名前には届きません。テストクラス、そのアノテーション付きのメンバー、アノテーション引数で使われるすべての名前は public でなければなりません。

入力中

テストファイルに構文エラーがある間 (たとえば dart run build_runner watch の下で)、ビルダーは警告をログに出し、既存の生成ファイルを変更せずに再び書き出します。ファイルが再び解析できるようになるまで、テストのその生成ファイルのインポートは動き続けます。既存の生成ファイルがなければ、何も書き出されません。

Spring (Java) との対応

@SpringBootTest(properties = "neon.shop.delivery-time=3d")
@ActiveProfiles({"dev", "test"})
class ShopTest {
  @Autowired Catalog catalog;

  @Test
  void hasTheSampleBooks() { ... }
}

重要な違い:

関連項目