Sub topic 1
What a Widget Test Is and How testWidgets Works
A widget test builds a Flutter widget inside a test environment, interacts with it the way a user would, and checks what ends up on screen. It runs on your machine with flutter test. It needs no emulator, phone, or window. This chapter covers the working model behind testWidgets and WidgetTester. Later chapters cover finders, matchers, and frame control in detail.
Prerequisites
This chapter assumes you have the following:
- Basic Dart syntax, including
asyncandawait. - Familiarity with
StatelessWidget,StatefulWidget, andsetState. - Knowledge of how to run
flutter testand what a unit test is. - A Flutter project whose
pubspec.yamllistsflutter_testunderdev_dependencies.flutter createadds it for you.
dev_dependencies:
flutter_test:
sdk: flutterWhere widget tests fit
Flutter has three common test levels. They differ in what they run and how fast they are.
| Level | Runs | Typical target | Speed |
|---|---|---|---|
| Unit test | Dart VM, no Flutter framework | Functions, classes, business logic | Fastest |
| Widget test | Dart VM with the real widget framework and a test engine | One widget or one screen | Fast |
| Integration test | Real device or emulator | The whole app | Slowest |
A widget test sits between the other two. It uses the real framework code for building, layout, gestures, and state. It replaces the platform: there is no real screen, no real clock, and no real plugin code. This makes it a good place to check that a screen shows the right thing for a given state and responds correctly to taps and typing.
The working model
Three pieces work together in every widget test.
testWidgetsregisters a test case, liketestdoes. The difference is that it also sets up the Flutter testing environment and passes you a tester.WidgetTesteris the object you receive. You use it to build widgets, simulate input, and move time forward.- The test binding is the hidden engine room.
testWidgetsinitializesTestWidgetsFlutterBinding(in practice, anAutomatedTestWidgetsFlutterBinding). It replaces the normal scheduler, clock, and rendering pipeline with controllable versions.
The signature looks like this:
void testWidgets(
String description,
Future<void> Function(WidgetTester tester) callback, {
bool? skip,
Timeout? timeout,
bool semanticsEnabled = true,
TestVariant<Object?> variant = const DefaultTestVariant(),
dynamic tags,
})The callback is asynchronous because most WidgetTester methods return a Future. You must await them.
The environment you get
Knowing the defaults explains many surprises:
- The test surface is 800 by 600 logical pixels with a device pixel ratio of 1.0. Layouts that need more room can overflow in tests even when they look fine on your phone.
- Time is fake. Frames are not produced automatically on a timer. Nothing redraws until you ask, and a
Future.delayedinside the widget completes only when you advance the fake clock. - Text is drawn with a test font called Ahem, in which every glyph is a solid square. Text still takes up space and can be found by its string. It just does not look like real text in screenshots.
- Platform channels and plugins return nothing unless you mock them.
A first test
This test builds a counter, taps its button, and checks the result.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('$_count')),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _count++),
child: const Icon(Icons.add),
),
);
}
}
void main() {
testWidgets('counter increments when the button is tapped',
(WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Counter()));
expect(find.text('0'), findsOneWidget);
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}Save it as test/counter_test.dart and run flutter test. The walkthrough follows.
tester.pumpWidgetinflates the widget tree and renders one frame. WrappingCounterinMaterialAppsupplies the ancestors that Material widgets need.find.text('0')is a finder. It describes a widget to look for but does not search until an assertion uses it.expect(..., findsOneWidget)is a matcher. It runs the search and passes if exactly one widget matches.tester.tapdispatches a pointer down and up event at the center of the matched widget. This callsonPressed, which callssetState.setStateonly marks the widget dirty. The tree is not rebuilt until a frame runs, sotester.pump()triggers that frame.- The last two
expectcalls check the rebuilt tree.
The lifecycle of one test
The order of events is the same in every widget test.
After your callback finishes, the framework unmounts the tree and checks for leftovers. It reports an error if a timer is still pending or if an exception was thrown during a frame. This is why a widget test can fail even though every expect passed.
Options worth knowing
You will rarely need the optional parameters at first, but they are useful:
skip: trueregisters the test without running it. The report shows it as skipped.timeoutoverrides the default 30 second limit. In practice a widget test should finish in milliseconds, so a timeout usually means an infinite animation or a missingawait.semanticsEnabledistrueby default. The semantics tree is built during the test, so you can use semantics-based finders and checks.variantruns the same body once per value.TargetPlatformVariant.all()is a common example.tagslets you select tests withflutter test --tags.
You can also run a single test by name:
flutter test test/counter_test.dart --plain-name 'counter increments'Common errors
These problems account for most first-week failures.
Using `test` instead of `testWidgets`
The plain test function does not create a tester or initialize the binding. Anything that touches widgets fails with a binding error. Use testWidgets whenever you call pumpWidget.
Forgetting `await`
If you write tester.pumpWidget(...) without await, the test body can reach expect before the tree exists. Then findsOneWidget fails for no obvious reason. Await every tester call that returns a Future.
Missing ancestors
A widget that uses Text, Scaffold, Theme, or MediaQuery needs ancestors to exist. Pumping a bare widget often produces errors such as these:
No Directionality widget foundNo MediaQuery widget ancestor foundNo Material widget found
Wrap the widget in MaterialApp, and in Scaffold if it needs one, as the first example does.
Forgetting to pump after a change
Taps and text entry change state, but the tree is stale until the next frame. If an assertion shows the old value, add await tester.pump() after the interaction.
Pending timers
A Timer or Future.delayed that is still scheduled when the test ends produces A Timer is still pending even after the widget tree was disposed. Cancel timers in dispose, or advance the fake clock past them before the test ends.
Real asynchronous work
The test clock is fake, so real I/O such as file access or network calls can hang. Replace those dependencies with fakes. For rare cases that truly need real async behavior, tester.runAsync runs a callback outside the fake zone.
What a widget test should and should not check
Good widget tests check behavior a user can observe: text shown, buttons enabled or disabled, a list that grows after input, a dialog that appears. They are weaker for checking exact pixel positions or private implementation details. A test that reaches into private state breaks on a harmless refactor, while a test that taps and reads the screen survives it.
Widget tests also cannot confirm that your app works on a particular device. They do not exercise real rendering, platform views, or plugin behavior. Use integration tests for that and keep widget tests for fast, focused feedback.
Summary of the model
testWidgetscreates a tester and a fake-time environment.pumpWidgetbuilds the tree. Finders describe what to look for. Matchers run the search and assert.- User actions change state, and
pumpproduces the frame that shows the change. - After the test, leftover timers or frame exceptions fail it.
Exercise
A test taps a button whose handler calls setState to change a label from "Off" to "On". The test then runs expect(find.text('On'), findsOneWidget) and fails, though the app works when run manually. What is the most likely cause, and how do you fix it?
Show answer
The test did not run a frame after the tap. setState only marks the widget dirty, and with the test binding no frame runs until you ask. Add await tester.pump() between the tap and the expect. Also check that the tap call itself was awaited.
Exercise
You write test('shows a title', (tester) async { ... }) and call tester.pumpWidget inside it. What goes wrong, and what is the fix?
Show answer
Plain test does not create a WidgetTester or initialize the test binding, so the body cannot use widget-testing APIs (there is no tester parameter to receive). Change test to testWidgets, which supplies the WidgetTester and sets up the binding.
Exercise
Why can a widget test pass on your laptop's layout but fail with a RenderFlex overflow, even though the screen looks fine on a phone?
Show answer
The default test surface is 800 by 600 logical pixels at a pixel ratio of 1.0 and uses the Ahem font, whose glyphs are solid squares of the font size. Text can occupy different widths than on a real device. Fix the layout so it handles the space, or set the test surface size explicitly for the test.