Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 73 ยท Quality and performance

Unit and Widget Testing

Learn Flutter testing with flutter_test: unit tests, testWidgets, pump and finders, mocking with mocktail and golden tests, plus a mini test harness you can run.

An app you cannot test is an app you are afraid to change. Flutter ships with a testing framework, flutter_test, that covers three levels: unit tests for plain Dart logic, widget tests that build a widget in a fake environment and interact with it, and integration tests that drive the real app on a device. This lesson covers the first two plus golden (screenshot) tests. Integration tests come in the next lesson.

The big surprise for newcomers: widget tests are fast. They run on your computer's Dart VM with no emulator, no real rendering to a screen and a fake clock. Hundreds of them finish in seconds, so you can run them on every save.

Real vs stand-in. The Dart code below is real flutter_test code, shown read-only because the site has no Dart or Flutter runtime. The live examples are JavaScript stand-ins: a tiny test harness with pump and finders that shows how the real framework thinks.

Three kinds of test

Unit Plain Dart logic. Milliseconds.
Widget Build one widget, tap, check.
Integration The whole app on a device.

Many unit tests, a good number of widget tests, a few integration tests.

1 / 2

Unit tests

Test pure Dart code with test, group and expect. Put files in test/ and end their names with _test.dart.

DART
// lib/cart.dart
class Cart {
  final _lines = <String, int>{};

  void add(String sku, {int quantity = 1}) {
    if (quantity <= 0) throw ArgumentError.value(quantity, 'quantity');
    _lines.update(sku, (q) => q + quantity, ifAbsent: () => quantity);
  }

  int get itemCount => _lines.values.fold(0, (a, b) => a + b);
}

// test/cart_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/cart.dart';

void main() {
  group('Cart', () {
    late Cart cart;

    setUp(() {
      cart = Cart();           // a fresh object for every test
    });

    test('starts empty', () {
      expect(cart.itemCount, 0);
    });

    test('adding the same sku twice accumulates', () {
      cart.add('pen');
      cart.add('pen', quantity: 2);
      expect(cart.itemCount, 3);
    });

    test('rejects zero quantity', () {
      expect(() => cart.add('pen', quantity: 0), throwsArgumentError);
    });
  });
}

Run them with flutter test. The pieces:

  • group bundles related tests under one name.
  • setUp runs before each test, so tests never share state. tearDown runs after each one.
  • expect(actual, matcher) compares a value with a matcher: equals, isTrue, contains('x'), isNull, closeTo(1.0, 0.01), throwsA(isA<StateError>()). A plain value means equals.

Good unit tests are small, name the behavior in plain English, and check one idea each. This works best when logic lives in plain classes instead of inside widgets, which is one reason architecture layers matter.

Widget tests

testWidgets gives you a WidgetTester. You build a widget, find parts of it, interact, and assert.

DART
class CounterButton extends StatefulWidget {
  const CounterButton({super.key});
  @override
  State<CounterButton> createState() => _CounterButtonState();
}

class _CounterButtonState extends State<CounterButton> {
  int _taps = 0;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => setState(() => _taps++),
      child: Text('Taps: $_taps'),
    );
  }
}

// test/counter_button_test.dart
void main() {
  testWidgets('tapping increases the label', (WidgetTester tester) async {
    await tester.pumpWidget(
      const MaterialApp(home: Scaffold(body: CounterButton())),
    );

    expect(find.text('Taps: 0'), findsOneWidget);

    await tester.tap(find.byType(ElevatedButton));
    await tester.pump();           // run the rebuild

    expect(find.text('Taps: 1'), findsOneWidget);
    expect(find.text('Taps: 0'), findsNothing);
  });
}

Three ideas to understand:

1. pumpWidget builds, pump advances a frame. Nothing rebuilds on its own in a test, because there is no real frame loop. After tap, the widget is marked dirty (see setState), but the UI is stale until you call pump(). Forgetting it is the number one beginner mistake.

2. pump(Duration) moves the fake clock. Animations run on a fake clock too. await tester.pump(const Duration(milliseconds: 300)) jumps 300 ms. pumpAndSettle() keeps pumping until no frames are scheduled, which is handy for transitions, but it throws a timeout if something animates forever (a spinner, for example). Use plain pump for infinite animations.

3. Finders locate widgets.

Finder Finds
find.text('Save') A Text widget with exactly that string
find.byType(Switch) Widgets of a type
find.byKey(const Key('email')) A widget with that key (see Keys)
find.byIcon(Icons.add) An Icon showing that icon
find.widgetWithText(ElevatedButton, 'Go') A button that has the text inside
find.descendant(of: a, matching: b) Narrow a search

The matching assertions are findsOneWidget, findsNothing, findsNWidgets(3) and findsAtLeastNWidgets(1). Interactions: tap, enterText(finder, 'hi'), drag(finder, Offset(0, -300)), longPress, fling.

Prefer finding by key or by what the user sees (text, icon, semantics label) rather than by position in the tree. A test that says "second child of the third Column" breaks when you add padding.

Wrapping the widget under test

Real widgets read Theme, MediaQuery, Navigator and providers from the BuildContext. In a test there are none, so you wrap the widget in what it needs. A common helper:

DART
Widget wrap(Widget child) => MaterialApp(home: Scaffold(body: child));

If the widget needs Provider or Riverpod, wrap it in ChangeNotifierProvider or ProviderScope with test overrides (Provider, Riverpod).

Stand-in: a mini widget test harness

This harness has a tiny widget tree, a dirty flag, and pump. It reproduces the key lesson: a tap marks dirty, and the screen only changes after a pump.

JS Mini WidgetTester: tap, then pump

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "stale before pump" lines are not failures of the harness, they are the behavior of the real WidgetTester too. Leave out pump() in a real test and your expect checks the old tree.

Mocking with mocktail

Widgets and logic often depend on things you do not want in a test: a network client, a database, the clock. Hide them behind an interface (a class or abstract class), then pass a fake. The mocktail package makes fakes without code generation.

DART
import 'package:mocktail/mocktail.dart';

abstract class WeatherApi {
  Future<double> temperatureFor(String city);
}

class MockWeatherApi extends Mock implements WeatherApi {}

void main() {
  test('formats the temperature', () async {
    final api = MockWeatherApi();
    when(() => api.temperatureFor('Oslo')).thenAnswer((_) async => 3.5);

    final service = WeatherService(api);
    expect(await service.label('Oslo'), '3.5 ยฐC in Oslo');

    verify(() => api.temperatureFor('Oslo')).called(1);
  });

  test('propagates failures', () {
    final api = MockWeatherApi();
    when(() => api.temperatureFor(any())).thenThrow(Exception('offline'));
    expect(WeatherService(api).label('Rome'), throwsException);
  });
}

when(() => call).thenAnswer(...) stubs a call (use thenAnswer for futures), verify checks it happened, and any() matches any argument (register fallback values for custom types with registerFallbackValue). Do not mock everything: mock the edges (network, storage), and use the real objects for your own logic. For HTTP, you can also inject a fake client; HTTP requests and JSON shows the shape.

Stand-in: a fake that records calls

The idea behind a mock is simple: replace the dependency with an object that returns canned answers and remembers how it was called.

JS A hand-written mock with when and verify

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Golden tests

A golden test renders a widget and compares it, pixel for pixel, with a saved image (the "golden file"). It catches accidental visual changes.

DART
testWidgets('profile card looks right', (tester) async {
  await tester.pumpWidget(wrap(const ProfileCard(name: 'Ada')));

  await expectLater(
    find.byType(ProfileCard),
    matchesGoldenFile('goldens/profile_card.png'),
  );
});

Create or update the images with flutter test --update-goldens, review them in your pull request like code, and commit them. Two cautions: by default tests draw text with a placeholder font, so goldens look blocky unless you load real fonts, and rendering differs slightly between operating systems, so generate goldens on the same platform your CI uses. Use goldens sparingly for stable, important components, not for every screen.

Habits that keep tests healthy

  • Name tests as sentences: 'shows an error when the email is empty'.
  • Keep tests independent: build fresh objects in setUp; never rely on test order.
  • Test behavior, not implementation: assert on what the user sees, not on private fields.
  • Make async deterministic: never use real Future.delayed sleeps; use pump(duration) or fake timers (fakeAsync).
  • Run in CI: flutter test --coverage produces coverage/lcov.info, which the CI lesson uses.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After tester.tap(find.byType(ElevatedButton)), the label still shows the old value. What is missing?

    Tests have no automatic frame loop. tap marks the widget dirty, and pump() runs the rebuild.
  2. 2. What does pumpAndSettle do?

    It keeps pumping until animations finish. It times out if something animates forever, such as a looping spinner.
  3. 3. Which finder is the most robust way to locate a text field in many layouts?

    Keys and visible text survive layout changes. Position-based finders break when you add padding or wrappers.
  4. 4. Why mock the network client in a unit test?

    A mock removes the real network, so the test is quick, repeatable and can simulate errors on demand.
  5. 5. How do you create or refresh golden files?

    Run flutter test --update-goldens, review the changed images and commit them.

Summary

  • Flutter has unit tests (test, expect), widget tests (testWidgets, WidgetTester) and integration tests; widget tests run fast on the Dart VM.
  • In a widget test, pumpWidget builds, pump runs a frame, and pump(duration) advances the fake clock. Always pump after an interaction.
  • Find widgets by key, type, text or icon, and assert with findsOneWidget and friends.
  • Wrap widgets in the MaterialApp, providers or themes they need.
  • Use mocktail to replace the edges (network, storage) with fakes, and golden tests sparingly for stable visuals.

Next: Integration Tests and CI