Skip to main content

09 - Widget Testing and Golden Tests: Automated Visual Quality

Widget and golden tests in Flutter: pump and pumpAndSettle, mocks and fakes, goldens that fail in CI, tolerance and Alchemist. Listings analysed, Flutter 3.44.

What do you think about this article?

09 - Widget Testing and Golden Tests: Automated Visual Quality
Flutter AvanzatoPhoto:Amarnath RadhakrishnanPexels

At a Glance

Widget and golden tests in Flutter: pump and pumpAndSettle, mocks and fakes, goldens that fail in CI, tolerance and Alchemist. Listings analysed, Flutter 3.44.

What a widget test proves (and what it does not)

A widget test builds a single widget inside a fake environment, makes it interact with taps and text, and checks that the widget tree is the expected one. The official testing overview places it between the unit test (one function) and the integration test (the app on a device): it is more complete than the first and much faster than the second, because there is no real window. A golden test is a widget test that, instead of looking for a text, compares the drawn image with a reference PNG file saved earlier.

What these tests do not prove: that the app is fast, that it works on a customer's phone, that the server responds. The next article exists for that, on integration testing and DevTools. Here the case is a cart product row, the same idea as the article on the BLoC pattern, written without dependencies to keep the tests readable.

A statement of method: Flutter 3.44.2 is installed on this machine and flutter analyze compiles all the listings in this article without errors. However I have not run the tests: so I have no observed output to show you, and where I write what happens I derive it from the source code of flutter_test or from the documentation, citing them. For every block the category is "output deduced, not run".

The widget under test

The product row shows the name, a + button and the row total. The amount is in cents (an integer) and is formatted only at the end, to avoid decimal rounding errors. The button carries a ValueKey: a stable key is the most solid way to find a widget again in a test, because it depends neither on the icon nor on the text, which change with a translation. In the same file there is a list that loads from a repository: it serves the section on mock objects.

The widget under test: ProductTile and ProductListPage (analysed, not run)
import 'package:flutter/material.dart';

String formatCents(int cents) => '${(cents / 100).toStringAsFixed(2)} €';

/// A product row with a quantity selector and a row total.
class ProductTile extends StatefulWidget {
  const ProductTile({super.key, required this.name, required this.priceCents});

  final String name;
  final int priceCents;

  @override
  State<ProductTile> createState() => _ProductTileState();
}

class _ProductTileState extends State<ProductTile> {
  int _quantity = 0;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(widget.name),
      subtitle: Text('Total: ${formatCents(widget.priceCents * _quantity)}'),
      trailing: IconButton(
        key: const ValueKey('add'),
        icon: const Icon(Icons.add),
        onPressed: () => setState(() => _quantity++),
      ),
    );
  }
}

abstract interface class ProductRepository {
  Future<List<String>> fetchNames();
}

/// List loaded from a repository: loading, error or data.
class ProductListPage extends StatelessWidget {
  const ProductListPage({super.key, required this.repository});

  final ProductRepository repository;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<String>>(
      future: repository.fetchNames(),
      builder: (context, snapshot) {
        if (snapshot.hasError) return const Text('Network error');
        if (!snapshot.hasData) return const CircularProgressIndicator();
        return Column(children: [for (final n in snapshot.data!) Text(n)]);
      },
    );
  }
}

Two choices affect the tests. ProductTile is a StatefulWidget with an internal quantity, so the result of a tap is seen only after the framework rebuilds. ProductListPage receives the repository from outside instead of creating it: that is the reason it can be replaced with a fake in tests, and the idea is the same as the dependency injection discussed in the architecture article.

pump, pumpAndSettle and fake time

In a test time does not flow on its own: you advance it. tester.tap sends only the press and the release, and the framework does not rebuild until you ask for a frame with pump(). The official guide on taps and text says so explicitly: after an interaction you call pump() or pumpAndSettle(). The first test below shows the case: tap, pump(), check.

Two tests: the pump after the tap, and the indicator that never ends (not run)
import 'package:fa/product_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('a tap on + brings the row total to 2.50 €', (tester) async {
    await tester.pumpWidget(
      const MaterialApp(home: Scaffold(body: ProductTile(name: 'Pen', priceCents: 250))),
    );
    expect(find.text('Total: 0.00 €'), findsOneWidget);

    await tester.tap(find.byKey(const ValueKey('add')));
    // Without this line the state has changed but the frame has not been drawn.
    await tester.pump();

    expect(find.text('Total: 2.50 €'), findsOneWidget);
  });

  testWidgets('an indicator that spins forever blocks pumpAndSettle', (tester) async {
    await tester.pumpWidget(
      const MaterialApp(home: Scaffold(body: CircularProgressIndicator())),
    );

    // Advance fake time by one second: enough to see the indicator.
    await tester.pump(const Duration(seconds: 1));
    expect(find.byType(CircularProgressIndicator), findsOneWidget);

    // pumpAndSettle would not terminate: we limit it and expect the error.
    await expectLater(
      tester.pumpAndSettle(const Duration(milliseconds: 100), EnginePhase.sendSemanticsUpdate, const Duration(seconds: 2)),
      throwsA(isA<FlutterError>()),
    );
  });
}

In the first test the line with the comment explains the rule: if you remove await tester.pump(), the internal state has changed but the widget shown has not, and the assertion on the text "2.50 €" fails. Note the format: the text produced by toStringAsFixed(2) uses the decimal point, because it does not depend on the language; if you want the comma you must format with the intl package. The second test is about a typical mistake. The source code of pump in the widget_tester.dart file states that pump(duration) "makes the framework believe that it has lost frames for that duration": it advances the fake clock, it does not really wait.

pumpAndSettle, from the Flutter 3.44.2 source, repeats pump with a 100 millisecond step until there are no more scheduled frames, and after a timeout of 10 minutes (fake time) throws FlutterError('pumpAndSettle timed out'). A CircularProgressIndicator requests frames forever, so it stops only because of the timeout. The argument is called timeout and not maxDuration, as you read in many examples that do not compile; in the test I brought it down to two seconds and wrote the assertion on the error, so the behaviour is documented by the test itself.

  • pump(): one frame, without advancing time.
  • pump(duration): one frame after advancing the fake time by the duration.
  • pumpAndSettle(): frames every 100 ms until the screen is still, or an error after the timeout.

The choice depends on the question you are asking. If you want to check an intermediate state of an animation use pump(duration), because it lets you stop halfway; if you want to wait for the end of a transition use pumpAndSettle(); if the screen contains perpetual animations (indicators, video) you cannot use the second and you must advance time by hand.

Mock objects: mocktail or a hand-written fake

When the widget depends on network or database, the test must not touch them. You have two ways. The first is a hand-written fake: a class that implements the interface and returns what is needed. It is the clearest and requires no libraries. The second is a package: mocktail (published by felangel.dev, version 1.0.5 of 2026-04-10 on pub.dev) works without code generation, while mockito (published by dart.dev, version 5.8.1) requires build_runner to generate the classes. For attribution: mocktail is not from the Dart team, as some articles say.

Two tests of the list: a mock with mocktail and a hand-written fake (not run)
import 'package:fa/product_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';

class MockProductRepository extends Mock implements ProductRepository {}

class FailingRepository implements ProductRepository {
  @override
  Future<List<String>> fetchNames() async => throw Exception('network down');
}

void main() {
  testWidgets('shows the names and calls the repository only once', (tester) async {
    final repo = MockProductRepository();
    when(() => repo.fetchNames()).thenAnswer((_) async => ['Pen', 'Notebook']);

    await tester.pumpWidget(MaterialApp(home: Scaffold(body: ProductListPage(repository: repo))));
    expect(find.byType(CircularProgressIndicator), findsOneWidget);

    await tester.pumpAndSettle();

    expect(find.text('Pen'), findsOneWidget);
    expect(find.text('Notebook'), findsOneWidget);
    verify(() => repo.fetchNames()).called(1);
  });

  testWidgets('with the network down it shows the error message', (tester) async {
    await tester.pumpWidget(
      MaterialApp(home: Scaffold(body: ProductListPage(repository: FailingRepository()))),
    );
    await tester.pumpAndSettle();
    expect(find.text('Network error'), findsOneWidget);
  });
}

In the first test when(() => repo.fetchNames()) programs the response and verify(...).called(1) checks that the page called the repository only once: if one day a refactoring made it call on every rebuild, this test would flag it. Before pumpAndSettle the loading indicator must be visible, which is why the findsOneWidget assertion comes first. The second test uses FailingRepository, a three-line fake, to cover the error branch: testing errors is the strongest reason to have a programmable fake.

Golden tests: the image as an assertion

The golden test draws the widget and compares it pixel by pixel with a PNG. It is useful when the defect you fear is visual and not logical: a shifted alignment, a changed colour, a text that wraps. Before writing it you set the size of the test window. Many examples use tester.binding.window.physicalSizeTestValue, today replaced by tester.view, which offers physicalSize and devicePixelRatio and is restored with tester.view.reset.

A golden test with fixed size and density (not run)
import 'package:fa/product_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('ProductTile on a narrow screen, 2x', (tester) async {
    tester.view
      ..physicalSize = const Size(400, 120)
      ..devicePixelRatio = 2.0;
    addTearDown(tester.view.reset);

    await tester.pumpWidget(
      const MaterialApp(home: Scaffold(body: ProductTile(name: 'Pen', priceCents: 250))),
    );

    await expectLater(
      find.byType(ProductTile),
      matchesGoldenFile('goldens/product_tile.png'),
    );
  });
}

The key goldens/product_tile.png is relative to the folder of the test file: the default comparator, LocalFileComparator, computes the path starting from the directory the test was loaded from. If the file does not exist, the source says the comparison fails with "Could not be compared against non-existent file". It is created with flutter test --update-goldens, a flag that exists in the flutter test help in this version and that rewrites all the PNGs of the tests that were run: always look at the diff in review before accepting. To run a single test use --plain-name or --name; the -k option that appears in some guides does not exist.

Why the same golden passes here and fails in CI

The main cause is in the text. The source of matchesGoldenFile explains that by default Flutter uses the "Ahem" font, which draws squares in place of characters, and that a golden with real fonts generated on Windows probably differs from the one produced on another system, or with another Flutter version. There are two ways: load a font from the assets with FontLoader (the source shows it with Roboto) and regenerate the PNGs on the same platform and version the CI uses, or accept Ahem's squares and test the structure instead of the character.

For small rendering differences the exact comparator is too strict. The Flutter source (goldens.dart) shows how to write a comparator with tolerance, and the following block is a version of it: diffPercent is the fraction of different pixels, and 0.001 means 0.1%.

A comparator with 0.1% tolerance, valid for the whole test folder (not run)
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';

/// Comparator that accepts up to [precisionTolerance] of different pixels.
class TolerantGoldenComparator extends LocalFileComparator {
  TolerantGoldenComparator(super.testFile, {required this.precisionTolerance});

  final double precisionTolerance; // fraction, 0.001 = 0.1% of the pixels

  @override
  Future<bool> compare(Uint8List imageBytes, Uri golden) async {
    final result = await GoldenFileComparator.compareLists(
      imageBytes,
      await getGoldenBytes(golden),
    );
    final passed = result.passed || result.diffPercent <= precisionTolerance;
    if (passed) {
      result.dispose();
      return true;
    }
    final error = await generateFailureOutput(result, golden, basedir);
    result.dispose();
    throw FlutterError(error);
  }
}

Future<void> testExecutable(FutureOr<void> Function() testMain) async {
  // As in the Flutter source example: PNGs are looked up in test/.
  goldenFileComparator = TolerantGoldenComparator(
    Uri.parse('test/flutter_test_config.dart'),
    precisionTolerance: 0.001,
  );
  await testMain();
}

The flutter_test_config.dart file is looked up by flutter test in the test folder and in the parent ones, and its testExecutable function wraps every test file (the flutter_test documentation describes it). Here it replaces the default comparator with ours, built as in the source example: PNGs are looked up in the test/ folder starting from the project root, where flutter test is normally launched. I did not run it, so if your tests live in subfolders check the PNG paths. The tolerance has a cost you must know: with 0.1% on a 400 by 120 pixel screen at density 2, that is 192,000 pixels, up to about 192 different pixels pass, and a thin one-line border that disappears can sit under the threshold. Keep it low and raise it only when faced with a demonstrated difference between two machines.

Alchemist: many scenarios in a single PNG

The alchemist package (Betterment, version 0.14.1 of 2026-10-08) organises several scenarios of the same view into one image and separates two kinds of golden, as its README explains: "platform" tests, with readable text, to be run locally, and "CI" tests, in which text is replaced by coloured rectangles and the font is always Ahem, so that the result does not depend on the system. It also has a difference threshold (diffThreshold, with a default value of zero). The old golden_toolkit, often cited alongside, shows as discontinued on pub.dev, with the last version (0.15.0) of 2023-02-21.

Two scenarios of the same row in a single golden (analysed, not run)
import 'package:alchemist/alchemist.dart';
import 'package:fa/product_list.dart';
import 'package:flutter/material.dart';

void main() {
  goldenTest(
    'ProductTile: short and long names',
    fileName: 'product_tile_scenarios',
    builder: () => GoldenTestGroup(
      scenarioConstraints: const BoxConstraints(maxWidth: 360),
      children: [
        GoldenTestScenario(
          name: 'short name',
          child: const ProductTile(name: 'Pen', priceCents: 250),
        ),
        GoldenTestScenario(
          name: 'long name',
          child: const ProductTile(
            name: 'Squared notebook with hard cover',
            priceCents: 480,
          ),
        ),
      ],
    ),
  );
}

The API has no devices parameter, as some examples show: scenarios are described with GoldenTestGroup and GoldenTestScenario, each with a name that ends up in the image. This form is useful precisely for edge cases like the long name of the second scenario, which shows whether the text wraps or is truncated without having to write two separate tests. The two destination folders, for the "ci" PNGs and for the platform ones, should both be under version control.

What you can do now

You can write a widget test that finds the button again by key, you know when pump is needed and why pumpAndSettle does not finish with an endless indicator, you can choose between a hand-written fake and a mock, and you know where goldens break between one machine and another. The next step is a test that runs on a real device: go to integration testing and DevTools. If you want to check the state of a Bloc without an interface, go back to BLoC in depth; and if you have not yet chosen between Riverpod and BLoC, the criterion is in the comparison between Riverpod 3.0 and BLoC 9.

Sources

  • Testing Flutter apps - role of widget tests compared with unit and integration tests, accessed 2026-11-12
  • Tap, drag, and enter text - pump() and pumpAndSettle() after an interaction, accessed 2026-11-12
  • Flutter 3.44.2 flutter_test source (widget_tester.dart, goldens.dart, _goldens_io.dart, matchers.dart) - signatures and default values of pump and pumpAndSettle, LocalFileComparator, Ahem font, comparator with tolerance; read in ~/flutter/packages/flutter_test/lib/src, 2026-11-12
  • alchemist on pub.dev - platform tests and CI tests, GoldenTestGroup, diffThreshold, accessed 2026-11-12
  • mocktail on pub.dev and mockito on pub.dev - publishers and versions, accessed 2026-11-12 (pub.dev API data)
  • golden_toolkit on pub.dev - discontinued package, accessed 2026-11-12

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects