テスト
テストの Bean はコンテナーのもの (そのプロキシ) なので、状態はアプリと同じようにテストでも追跡されます。
使う理由
状態はウィジェットではなく Bean の中にあるので、そのほとんどはウィジェットなしでテストできます。フィールドに代入し、計算された値を読み、Future を待ちます。
例
final app = springBootTest(
springApplication,
overrides: [BeanOverride<CatalogClient>(FakeCatalog())],
);
test('another genre loads other books', () async {
final catalog = app.getBean<Catalog>()..genre = 'poetry';
expect((await catalog.books).first.title, 'poetry one');
});
インスタンスではなく Bean
手で作ったインスタンス (Basket(storage)) は、普通のオブジェクトです。フィールドは動きますが、何も追跡しません。テストは、アプリケーションから Bean を受け取ります: app.getBean<Basket>()。
状態とエフェクト
test('a computed value follows what it read', () {
final basket = app.getBean<Basket>();
basket.add(const Book('Dune', 10));
expect(basket.total, 10);
basket.coupon = 'TEN';
expect(basket.total, 9);
});
test('an effect runs for a change', () {
final basket = app.getBean<Basket>();
final storage = app.getBean<BasketStorage>();
storage.saved.clear();
basket.add(const Book('Dune', 10));
expect(storage.saved, isNotEmpty);
});
エフェクトは、代入したメソッドが戻るまでに実行されています。そのため、テストに pump も遅延も必要ありません。
非同期の状態
test('refresh keeps the last value meanwhile', () async {
final catalog = app.getBean<Catalog>();
await catalog.books;
final refreshed = catalog.books.refresh();
expect(catalog.books.state.isRefreshing, isTrue);
expect(catalog.books.state.hasValue, isTrue);
await refreshed;
expect(catalog.books.state.isLoading, isFalse);
});
ウィジェット
ウィジェットテストは、アプリを起動してタップします。概要 の Shop を使います。
testWidgets('a tap changes the total', (tester) async {
await tester.pumpWidget(
SpringApplicationWidget(
application: () => springApplication,
home: const Shop(),
),
);
await tester.pumpAndSettle();
expect(find.text('Total: 0.0'), findsOneWidget);
await tester.tap(find.text('Add Dune'));
await tester.pump();
expect(find.text('Total: 10.0'), findsOneWidget);
});