Testing

The beans of a test are the container's (their proxies), so the state is followed in a test as in the app.

Why

The state is in beans, not in widgets, so most of it is tested without a widget: assign a field, read a computed value, await a future.

Example

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');
});

A bean, not an instance

An instance made by hand (Basket(storage)) is a plain object: its fields work, nothing follows them. A test takes the bean from the application: app.getBean<Basket>().

State and effects

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);
});

An effect has run by the time the method that assigned returns, so a test needs no pump and no delay for it.

Asynchronous state

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);
});

Widgets

A widget test starts the app and taps. With the Shop of the overview:

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);
});

See also