TExcelTAD
Home › Flutter › Flutter Testing

Flutter Testing

Tests let you change code with confidence: a quick command tells you whether everything still works. Flutter supports three levels of automated tests:

Kind Tests Speed Package
Unit test A single function or class (no UI) Very fast test / flutter_test
Widget test One widget or screen, in a simulated environment Fast flutter_test
Integration test The whole app on a real device or emulator Slow integration_test

A healthy project has many unit tests, a good number of widget tests and a few integration tests. Test files live in the test/ folder and their names end in _test.dart.

Unit tests

A unit test calls your code and checks the result with expect(actual, matcher). Group related tests with group.

flutter · try it yourself
// lib/cart.dart
class Cart {
  final _prices = <double>[];
  void add(double price) {
    if (price < 0) throw ArgumentError('Price must be positive');
    _prices.add(price);
  }
  double get total => _prices.fold(0, (sum, p) => sum + p);
}

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

void main() {
  group('Cart', () {
    test('starts empty', () {
      expect(Cart().total, 0);
    });

    test('adds up prices', () {
      final cart = Cart()..add(2.5)..add(4);
      expect(cart.total, 6.5);
    });

    test('rejects negative prices', () {
      expect(() => Cart().add(-1), throwsArgumentError);
    });
  });
}
00:01 +3: All tests passed!

Widget tests

A widget test uses testWidgets, which gives you a WidgetTester. With it you:

  1. Build a widget: await tester.pumpWidget(...).
  2. Find widgets with find.text, find.byIcon, find.byType or find.byKey.
  3. Interact: tester.tap, tester.enterText, tester.drag.
  4. Rebuild after a change: await tester.pump() (one frame) or pumpAndSettle() (until animations finish).
  5. Check with matchers like findsOneWidget, findsNothing, findsNWidgets(2).

Here is the classic counter app from flutter create and a test for it:

flutter · try it yourself
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/main.dart';

void main() {
  testWidgets('Counter increments when + is tapped', (tester) async {
    await tester.pumpWidget(const MyApp());

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

    await tester.tap(find.byIcon(Icons.add));
    await tester.pump(); // rebuild after setState

    expect(find.text('0'), findsNothing);
    expect(find.text('1'), findsOneWidget);
  });
}
00:02 +1: All tests passed!

Testing text input

flutter · try it yourself
testWidgets('shows greeting after typing a name', (tester) async {
  await tester.pumpWidget(const MaterialApp(home: Scaffold(body: GreetingForm())));

  await tester.enterText(find.byType(TextField), 'Mia');
  await tester.tap(find.text('Greet me'));
  await tester.pump();

  expect(find.text('Hello, Mia!'), findsOneWidget);
});
00:02 +1: All tests passed!

Tip: Give important widgets a Key, e.g. ElevatedButton(key: const Key('submit'), …), and find them with find.byKey(const Key('submit')). Keys don't break when you change the button's label or translate the app.

Running tests

bash · try it yourself
flutter test
00:03 +5: All tests passed!

Run a single file, or see each test name with the expanded reporter:

bash · try it yourself
flutter test test/cart_test.dart --reporter expanded
00:00 +0: loading /my_app/test/cart_test.dart
00:01 +0: Cart starts empty
00:01 +1: Cart adds up prices
00:01 +2: Cart rejects negative prices
00:01 +3: All tests passed!

When a test fails, the output shows what was expected and what was found:

text
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞═══════════════
Expected: exactly one matching candidate
  Actual: _TextWidgetFinder:<Found 0 widgets with text "1": []>

Golden and integration tests (briefly)

  • Golden tests render a widget to an image and compare it with a saved PNG using matchesGoldenFile('card.png') — great for catching visual regressions.
  • Integration tests live in integration_test/, use the same WidgetTester API, and run on a device with flutter test integration_test.

Note: Widget tests run without a real device and without real network access. Inject fake services (for example a fake repository that returns fixed data) instead of calling real APIs in tests.

Test yourself

Which function builds a widget inside a widget test?

  1. tester.build()
  2. tester.pumpWidget()
  3. runApp()
  4. find.widget()

After tester.tap(...) triggers setState, what must you call before checking the new UI?

  1. tester.pump()
  2. tester.reset()
  3. setState again
  4. Nothing

Which matcher asserts a widget does not appear at all?

  1. findsOneWidget
  2. findsNothing
  3. isNull
  4. throwsError