テストクラス

springBootTest のテストは、Spring と同じ書き方でクラスとして書けます。ジェネレーター (spring_core_dart_generator。すでに dev 依存関係にあります) は、各クラスを同じ関数に変換し、test/spring_gen/<name>.test.spring.dart に書き出します。

使う理由

Spring の開発者は、@SpringBootTest、@Autowired、@Test を一目で読み取れます。テストクラスはその形を保ちます。クラスはテストの Bean とテストメソッドを持ち、その上のアノテーションがアプリケーションの起動方法を示します。

例

// test/checkout_test.dart
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

import 'spring_gen/checkout.test.spring.dart'; // test/spring_gen/ に生成される

@SpringBootTest(args: ['--shop.name=Night Books'])
@ActiveProfiles(['dev', 'test'])
@TestEnvironment({'SHOP_MAX_BASKET_SIZE': '25'})
class CheckoutTest {
  @Autowired()
  late ShopProperties properties;

  @Autowired()
  late Checkout checkout;

  @TestBean(name: 'sandbox')
  final gateway = FakeGateway();

  @Test()
  void propertiesFromTheCommandLineAndTheEnvironment() {
    expect(properties.name, 'Night Books');
    expect(properties.maxBasketSize, 25);
  }

  @Test('checkout pays through the fake')
  void pays() {
    checkout.pay(3);
    expect(gateway.charged, [3]);
  }
}

void main() => runSpringTests();

クラスのアノテーション

アノテーション springBootTest のパラメーター Spring
@SpringBootTest(application:, args:, properties:, resourceDirectories:, webEnvironment:) 最初の引数、args:、properties:、resourceDirectories:、webEnvironment: @SpringBootTest
@ActiveProfiles(['dev', 'test']) profiles: @ActiveProfiles
@TestPropertySource(properties: {...}, locations: [...]) properties:、propertyFiles: @TestPropertySource
@TestEnvironment({'NAME': 'value'}) systemEnvironment: なし
@DirtiesContext() setUp(app.markDirty) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
@AutoConfigureMockMvc() なし: MockMvc は常に動く @AutoConfigureMockMvc
@Testcontainers() コンテナ を参照 @Testcontainers

application は @SpringBootApplication を持つエントリーポイントへのパス ('bin/admin.dart') で、パッケージに複数ある場合にだけ必要です。パッケージ内のどこを指してもよいため、スターターのテストは test/ の下に独自のアプリケーションを置いて起動できます。

フィールド

アノテーション 付ける場所 得られるもの
@Autowired() late フィールド 各テストの前に設定される Bean (再起動後は新しいコンテキストの Bean)。@Qualifier('x') は複数の中から一つを選ぶ
@Value(r'${key}') late フィールド 変換されたプロパティ
@TestBean() 値を持つフィールド Bean を置き換える。BeanOverride と @TestBean を参照
@LocalServerPort() late int フィールド 本物のサーバーのポート
@CapturedOutput() late CapturedLogs フィールド 各テストのログ。キャプチャーしたログ を参照
@Nested('name') インスタンスを持つフィールド 同じコンテキストを使うテストのグループ
@Container() static フィールド Docker のコンテナ。コンテナ を参照

メソッド

アノテーション 意味
@Test([name]) テスト。名前がなければ、メソッド名を単語に分けたもの (addsABook は adds a book)。返された Future は待たれる
@DisplayName(name) テストの名前。@Test(name) より優先される
@Disabled([reason]) テストをスキップする (クラスや @Nested フィールドに付けると、そのすべて)。理由とともに表示される
@Tag(name) dart test --tags / --exclude-tags のためのタグ。複数可
@TestOptions(timeout:, retry:, testOn:, onPlatform:) test() のその他のオプション
@DirtiesContext() このテストの後に新しいコンテキスト
@BeforeAll() static。コンテキストの起動前に一度
@BeforeEach() 各テストの前。フィールドが注入された後
@AfterEach() 各テストの後。@DirtiesContext による再起動の前
@AfterAll() static。コンテキストが閉じた後に一度
@DynamicPropertySource() static。起動のたびに動的プロパティを登録する
@ContextInitializer() static。リフレッシュの前に実行されるイニシャライザー

テストはメソッドの順に実行されます。同じ前処理・後処理のアノテーションを持つ複数のメソッドは、クラス内の順に実行されます。

@SpringBootTest()
class OrdersTest {
  @Autowired()
  late Orders orders;

  @BeforeAll()
  static Future<void> startDatabase() async { ... }   // コンテキストの起動前

  @BeforeEach()
  void clear() => orders.clear();                      // この時点で Bean は注入済み

  @Test()
  @Tag('slow')
  @TestOptions(timeout: Timeout(Duration(seconds: 5)), retry: 2)
  Future<void> placesAnOrder() async { ... }

  @Test()
  @DirtiesContext()                                    // このテストの後に新しいコンテキスト
  void changesSharedState() { ... }
}

グループ: @Nested

Dart には内部クラスがないため、グループはそれ自身のクラスのインスタンスを持つフィールドです。同じコンテキストと Bean を使う group として実行されます。その @BeforeEach メソッドは外側のものの後に実行されます。

@SpringBootTest()
class BasketTest {
  @Nested('with one book')
  final withOneBook = WithOneBook();
}

class WithOneBook {
  @Autowired()
  late Basket basket;               // 外側のクラスと同じ Bean

  @BeforeEach()
  void addBook() => basket.add('Dune', 10);

  @Test()
  void costsItsPrice() => expect(basket.total, 10);
}

ネストしたクラスは、@TestBean フィールドや、@BeforeAll、@AfterAll、@DynamicPropertySource、@ContextInitializer メソッドを持てません。それらはコンテキストを所有する外側のクラスのものです。

クラスに付ける @DirtiesContext

クラスの各テストの後にコンテキストを再起動します。Spring の classMode = AFTER_EACH_TEST_METHOD です。Spring のクラスに対するデフォルト (AFTER_CLASS) は、各クラスが自分のコンテキストを起動するため、ここではいずれにせよすべてのクラスに当てはまります。classMode も methodMode もありません。

ビルドエラー

ジェネレーターはクラスをチェックし、final の @Autowired フィールド、置き換える型のない @TestBean フィールド、static な @Test メソッド、エントリーポイントでない application のパスといった誤りに対して、メッセージとともにビルドを止めます。ジェネレーター: テスト を参照してください。

Spring (Java) との対応

@SpringBootTest(args = "--shop.name=Night Books")
@ActiveProfiles({"dev", "test"})
class CheckoutTest {
  @Autowired ShopProperties properties;
  @TestBean(name = "sandbox") PaymentGateway gateway;
  static PaymentGateway gateway() { return new FakeGateway(); }

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

違い: フィールドだけ (コンストラクター注入はない)、main() => runSpringTests() は残す、グループは @Nested フィールド、そして @Tag、@Disabled、@TestOptions は package:test のライブラリのアノテーションを個々のテストに持ち込みます。

関連項目