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.
// 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:
- Build a widget:
await tester.pumpWidget(...). - Find widgets with
find.text,find.byIcon,find.byTypeorfind.byKey. - Interact:
tester.tap,tester.enterText,tester.drag. - Rebuild after a change:
await tester.pump()(one frame) orpumpAndSettle()(until animations finish). - Check with matchers like
findsOneWidget,findsNothing,findsNWidgets(2).
Here is the classic counter app from flutter create and a test for it:
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
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 withfind.byKey(const Key('submit')). Keys don't break when you change the button's label or translate the app.
Running tests
flutter test00:03 +5: All tests passed!
Run a single file, or see each test name with the expanded reporter:
flutter test test/cart_test.dart --reporter expanded00: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:
══╡ 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 sameWidgetTesterAPI, and run on a device withflutter 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?
- tester.build()
- tester.pumpWidget()
- runApp()
- find.widget()
After tester.tap(...) triggers setState, what must you call before checking the new UI?
- tester.pump()
- tester.reset()
- setState again
- Nothing
Which matcher asserts a widget does not appear at all?
- findsOneWidget
- findsNothing
- isNull
- throwsError