spring_boot_starter_test

spring_boot_starter_test は、テストに本物のアプリケーションを与えます。spring-boot-starter-test に当たる Dart のものです。springBootTest は @SpringBootTest、BeanOverride は @MockitoBean と @TestBean、MockMvc は MockMvc、ApplicationContextRunner は Spring Boot のランナー、コンテナは @ServiceConnection を使う Testcontainers に当たります。

テストは、main の中の普通の関数として、あるいは Spring のテストのようにアノテーション (@SpringBootTest()、@Autowired()、@Test()) を付けたクラスとして書きます。ジェネレーターはクラスを同じ関数に変換します。パッケージは test_api と matcher の上に作られているため、package:test でも flutter_test でも動きます。

使う理由

オブジェクトを手で生成する単体テストでは、アプリケーションが起動するかどうかは分かりません。設定ファイルがバインドされるか、Bean が互いを見つけるか、コントローラーがクライアントの期待どおりに応答するか、です。このパッケージは、本物のアプリケーションをテストの中で (多くのテストに対して一度だけ) 起動し、テストが必要なものだけを変えられるようにします。

セットアップ

# pubspec.yaml
dev_dependencies:
  spring_boot_starter_test: ^0.9.0
  test: ^1.25.0            # または flutter_test
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0

テストの前に dart run build_runner build (または watch) を実行してください。テストは、ジェネレーターがエントリーポイントのために書き出した springApplication と、テストクラスの生成コードを使います。

例

関数として:

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

import '../bin/spring_gen/main.spring.dart'; // 生成された springApplication

void main() {
  final gateway = FakeGateway();

  // 本物のショップを、下のテストのために一度だけ、偽のゲートウェイとともに起動する。
  final app = springBootTest(
    springApplication,
    profiles: ['test'],                              // application-test.yml を読む
    properties: {'shop.max-basket-size': 3},         // 他のすべてのソースより上
    overrides: [BeanOverride<PaymentGateway>(gateway)],
  );

  test('checkout pays through the fake', () {
    app.getBean<Checkout>().pay(10);
    expect(gateway.charged, [10]);
  });

  test('GET /api/books/1111 answers the book', () async {
    await app.mockMvc
        .get('/api/books/1111')
        .andExpect(status: 200, json: containsPair('title', 'Dune'));
  });
}

同じものをクラスとして:

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

@SpringBootTest(properties: {'shop.max-basket-size': 3})
@ActiveProfiles(['test'])
class CheckoutTest {
  @TestBean()
  final PaymentGateway gateway = FakeGateway(); // 唯一の PaymentGateway を置き換える

  @Autowired()
  late Checkout checkout;

  @Test()
  void paysThroughTheFake() {
    checkout.pay(10);
    expect((gateway as FakeGateway).charged, [10]);
  }
}

void main() => runSpringTests();
dart run build_runner build
dart test

内容

Spring (Java) との対応

@SpringBootTest(properties = "shop.max-basket-size=3")
@ActiveProfiles("test")
class CheckoutTest {
  @MockitoBean PaymentGateway gateway;
  @Autowired Checkout checkout;

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

重要な違い:

関連項目