Labs ICT
Pro Login

Testing in Flutter

Making sure your app works.

Testing in Flutter

Tests catch bugs before your users do. Flutter has excellent built-in support for unit tests, widget tests, and golden tests.

First, add the test dependency to your pubspec.yaml (it's already included by default for Flutter projects):

dev_dependencies:
  flutter_test:
    sdk: flutter

Unit tests verify a single function or class in isolation:

import 'package:flutter_test/flutter_test.dart';

int add(int a, int b) => a + b;

void main() {
  test('addition works correctly', () {
    expect(add(2, 3), equals(5));
    expect(add(-1, 1), equals(0));
    expect(add(0, 0), equals(0));
  });
}

For more complex scenarios, use group to organize related tests:

void main() {
  group('Calculator', () {
    test('addition', () {
      expect(add(2, 3), equals(5));
    });

    test('subtraction', () {
      expect(subtract(5, 3), equals(2));
    });
  });
}

Widget tests let you interact with and verify your UI:

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

void main() {
  testWidgets('counter increments', (WidgetTester tester) async {
    await tester.pumpWidget(
      const MaterialApp(
        home: Scaffold(
          body: CounterWidget(),
        ),
      ),
    );

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

    await tester.tap(find.byIcon(Icons.add));
    await tester.pump();

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

Golden tests capture a screenshot of your widget and compare it to a stored reference image. They're great for catching visual regressions:

testWidgets('button looks correct', (WidgetTester tester) async {
  await tester.pumpWidget(
    const MaterialApp(
      home: Scaffold(
        body: MyButton(label: 'Click Me'),
      ),
    ),
  );

  await expectLater(
    find.byType(MyButton),
    matchesGoldenFile('golden/my_button.png'),
  );
});

To update golden files when your UI changes intentionally, run:

flutter test --update-goldens

Run all your tests with:

flutter test

Or run a specific test file:

flutter test test/widget_test.dart

Aim for a mix of test types. Unit tests are fast and thorough. Widget tests verify user interactions. Golden tests protect your visual design.

Try it Yourself ->