Sub topic 11
Structuring tests with group, setUp and helpers
This chapter assumes you can already write a widget test with testWidgets, build a widget with pumpWidget, find it with finders, and tap it with WidgetTester. It shows how to keep a growing test file readable. You will use group to cluster tests, setUp to give each test fresh state, and helper functions to remove repeated code.
Why structure matters
A first widget test is often ten lines long. Real files hold dozens of tests, and most of them start with the same lines: wrap the widget in MaterialApp, pump it, find the same buttons. Copying those lines has three costs:
- A change to the widget's constructor means editing every test.
- Failure messages name a test, but a flat list of 40 names is hard to scan.
- State shared through top-level variables leaks from one test into the next.
Three tools address these problems:
| Tool | What it solves |
|---|---|
| `group` | Clusters related tests and prefixes their names |
| `setUp` | Resets shared state before every test |
| Helper functions | Remove repeated pumping, tapping and asserting code |
The widget under test
The examples use a small counter with a configurable start value and a change callback. The minus button is disabled at zero.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class StepCounter extends StatefulWidget {
const StepCounter({super.key, this.initial = 0, this.onChanged});
final int initial;
final ValueChanged<int>? onChanged;
@override
State<StepCounter> createState() => _StepCounterState();
}
class _StepCounterState extends State<StepCounter> {
late int _count = widget.initial;
void _change(int delta) {
setState(() => _count += delta);
widget.onChanged?.call(_count);
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
key: const Key('dec'),
icon: const Icon(Icons.remove),
onPressed: _count > 0 ? () => _change(-1) : null,
),
Text('$_count', key: const Key('count')),
IconButton(
key: const Key('inc'),
icon: const Icon(Icons.add),
onPressed: () => _change(1),
),
],
);
}
}Extracting helpers
Look for the lines that appear at the top of every test. Here they are the MaterialApp and Scaffold wrapper. Move them into a function that takes the WidgetTester as an argument and exposes only the parameters the tests vary.
Future<void> pumpCounter(
WidgetTester tester, {
int initial = 0,
ValueChanged<int>? onChanged,
}) {
return tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StepCounter(initial: initial, onChanged: onChanged),
),
),
);
}
Future<void> tapKey(WidgetTester tester, String key) async {
await tester.tap(find.byKey(Key(key)));
await tester.pump();
}
void expectCount(int expected) {
final text = find.byKey(const Key('count'));
expect(tester_widgetText(text), '$expected');
}The last helper calls a function that does not exist yet. A helper cannot reach tester unless it receives it, so expectCount needs the tester as a parameter. Here is the corrected version, which is the one the rest of the chapter uses:
void expectCount(WidgetTester tester, int expected) {
final text = tester.widget<Text>(find.byKey(const Key('count')));
expect(text.data, '$expected');
}Three habits make helpers worth having:
- Give a helper a name that states intent (
pumpCounter, notsetup1). - Pass
testerexplicitly. Helpers that do not need it, such as plain finder builders, should not take it. - Keep the assertion inside the test body when it is the point of the test. Use an assertion helper such as
expectCountfor checks that many tests repeat.
Grouping tests with group
group takes a description and a callback that holds tests and other groups. Groups can nest. The description of each enclosing group is prefixed to the test name, so a failure reads StepCounter increment adds one instead of adds one.
Resetting state with setUp
setUp registers a callback that runs before every test in its group, including tests in nested groups. Declare the variable as late in the group, then assign it in setUp. Each test then starts with a new, empty value.
setUp has no WidgetTester. The tester exists only inside a testWidgets body, so setUp is the place for plain Dart state: lists, fakes, counters. Pumping the widget stays in the test or in a helper.
void main() {
group('StepCounter', () {
late List<int> changes;
setUp(() {
changes = [];
});
group('initial state', () {
testWidgets('starts at zero by default', (tester) async {
await pumpCounter(tester);
expectCount(tester, 0);
});
testWidgets('starts at the given value', (tester) async {
await pumpCounter(tester, initial: 5);
expectCount(tester, 5);
});
});
group('increment', () {
testWidgets('adds one per tap', (tester) async {
await pumpCounter(tester, onChanged: changes.add);
await tapKey(tester, 'inc');
await tapKey(tester, 'inc');
expectCount(tester, 2);
expect(changes, [1, 2]);
});
});
group('decrement', () {
testWidgets('subtracts one per tap', (tester) async {
await pumpCounter(tester, initial: 3, onChanged: changes.add);
await tapKey(tester, 'dec');
expectCount(tester, 2);
expect(changes, [2]);
});
testWidgets('is disabled at zero', (tester) async {
await pumpCounter(tester);
final button = tester.widget<IconButton>(find.byKey(const Key('dec')));
expect(button.onPressed, isNull);
expect(changes, isEmpty);
});
});
});
}The changes list is reassigned before each test. Without setUp, the increment test would leave [1, 2] behind, and any later test that asserts isEmpty would fail only when the whole file runs. That kind of failure disappears when you run the test alone, which makes it hard to trace.
Order of execution
For each test, Dart's test runner calls the callbacks in a fixed order. Outer setUp callbacks run before inner ones, and tearDown callbacks run in the opposite direction.
Related hooks:
setUpAllandtearDownAllrun once per group, not once per test. Use them only for expensive, read-only resources. Never put mutable state there, because tests would share it.tearDownreleases things the test opened, such as a stream controller or a temporary file.addTearDownis called inside a test body and registers cleanup for just that test. It suits resources a test creates conditionally.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Mutable state declared as a top-level `final` and never reset | A test passes alone and fails in the full run | Declare it `late` in the group and assign it in `setUp` |
| Calling `tester.pumpWidget` in `setUp` | Compile error: no tester is in scope | Pump inside the test body or a helper |
| Hiding the key assertion inside a helper | A failing test points at a helper, not the intent | Keep the main `expect` in the test; share only repeated checks |
| Tests that rely on running in a certain order | Failures when you run one test by name | Make each test build its own widget and state |
| Helpers with many positional arguments | Calls like `pumpCounter(tester, 3, null, true)` are unreadable | Use named parameters with defaults |
File layout and running subsets
Put test files under test/, and end each name in _test.dart so flutter test finds it. Put shared helpers in a file that does not end in _test.dart, such as test/helpers/pump_app.dart, and import it from each test file. The runner then does not try to run the helper file as a test.
Group names make it easy to run a subset. The --plain-name option matches against the full test name, group prefixes included:
flutter test test/step_counter_test.dart --plain-name "StepCounter decrement"This runs both tests in the decrement group and skips the rest.
Exercise
Exercise
A test file declares final events = <String>[]; at the top level of main, outside any group. A test named "logs a tap" adds 'tap' to events, and a later test asserts expect(events, isEmpty). The second test passes when run alone and fails when the file runs in full. Why, and how do you fix it using the tools from this chapter?
Show answer
The list is created once and shared by every test in the file, so the first test's entry is still there when the second test runs. Alone, the second test sees an empty list. Fix it by declaring late List<String> events; inside the group and assigning events = []; in setUp, so each test gets a new list. setUp runs before every test, so the second test starts with an empty list whatever ran before it.
Exercise
You want a helper that pumps the counter and then taps the increment button three times. Which parameter must the helper take, and why can this work not go in setUp?
Show answer
It must take the WidgetTester, because pumping and tapping are done through the tester. setUp cannot do this work because it runs outside testWidgets, where no tester exists. Write the helper as a function that accepts tester and call it from each test body.