Sub topic 4
Grouping tests and sharing setup
This chapter assumes you can write a basic test with expect, and that you know what a late variable is in Dart. As a test file grows, you need a way to organize it and to avoid repeating the same setup code. The test runner gives you group, setUp, tearDown, setUpAll, tearDownAll and addTearDown for this. All of them come from package:flutter_test/flutter_test.dart.
Why structure matters
A flat file with fifteen test calls works, but it has two problems.
- Every test repeats the same lines that build the object under test.
- Failure output shows only the test name, so related tests are hard to scan.
group solves the second problem by giving tests a shared prefix. setUp solves the first by running a callback before every test.
group: naming and nesting
group(description, body) collects tests under a description. The runner builds each test's full name by joining the descriptions of all enclosing groups and the test itself with spaces. A test named contains the item inside the group after adding an item inside the group Cart is reported as Cart after adding an item contains the item.
Groups can nest to any depth. Nest them to describe a state ("after adding an item") instead of writing long test names that repeat the state.
import 'package:flutter_test/flutter_test.dart';
class Cart {
final List<String> _items = [];
List<String> get items => List.unmodifiable(_items);
bool get isEmpty => _items.isEmpty;
void add(String item) => _items.add(item);
void clear() => _items.clear();
}
void main() {
group('Cart', () {
late Cart cart;
setUp(() {
cart = Cart();
});
test('starts empty', () {
expect(cart.isEmpty, isTrue);
});
group('after adding an item', () {
setUp(() {
cart.add('apple');
});
test('is not empty', () {
expect(cart.isEmpty, isFalse);
});
test('contains the item', () {
expect(cart.items, ['apple']);
});
test('is empty again after clear', () {
cart.clear();
expect(cart.isEmpty, isTrue);
});
});
});
}The inner setUp can use cart because the outer setUp has already assigned it. Setup callbacks run from the outermost group inward, so each level can build on the one above it.
setUp and tearDown
setUp registers a callback that runs before each test in its scope. tearDown registers a callback that runs after each test in its scope, whether the test passed or failed.
Both callbacks can be async, and the runner waits for the returned Future to finish before moving on.
Use setUp to create fresh objects. Use tearDown to release things the test opened, such as stream controllers, files or timers.
The late pattern in the example above is the standard way to share an object. You declare the variable in the group body and assign it in setUp. Each test then gets a new instance, so one test cannot affect the next.
Order of execution
For a test inside nested groups, the runner does the following:
- Runs
setUpcallbacks from the outermost scope to the innermost. - Runs the test body.
- Runs
tearDowncallbacks from the innermost scope to the outermost.
setUpAll and tearDownAll run once per scope, not once per test. A setUpAll runs before the first test in its scope, and a tearDownAll runs after the last one.
import 'package:flutter_test/flutter_test.dart';
void main() {
setUpAll(() => print('setUpAll (file)'));
tearDownAll(() => print('tearDownAll (file)'));
setUp(() => print(' setUp outer'));
tearDown(() => print(' tearDown outer'));
group('inner', () {
setUp(() => print(' setUp inner'));
tearDown(() => print(' tearDown inner'));
test('one', () => print(' test one'));
test('two', () => print(' test two'));
});
}Running this prints the lines in this order:
setUpAll (file)
setUp outer
setUp inner
test one
tearDown inner
tearDown outer
setUp outer
setUp inner
test two
tearDown inner
tearDown outer
tearDownAll (file)Choosing the right hook
| Hook | Runs | Typical use |
|---|---|---|
| `setUp` | Before every test in scope | Create a fresh object under test or a fresh fake |
| `tearDown` | After every test in scope | Close controllers, cancel timers, reset globals |
| `setUpAll` | Once before the first test in scope | Expensive read-only work, such as loading a fixture file |
| `tearDownAll` | Once after the last test in scope | Delete a temporary directory created in `setUpAll` |
| `addTearDown` | After the current test, called from inside it | Clean up a resource created in one test only |
Prefer setUp over setUpAll by default. setUpAll creates one shared object, and any test that changes it can break the tests after it.
addTearDown for per-test cleanup
Sometimes only one test creates a resource. A tearDown for the whole group would then run for tests that never opened it. addTearDown registers a cleanup callback from inside the test body, right next to the line that creates the resource.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('stream controller emits added values', () async {
final controller = StreamController<int>();
addTearDown(controller.close);
controller.add(1);
controller.add(2);
expect(await controller.stream.take(2).toList(), [1, 2]);
});
}Callbacks registered with addTearDown run after the test finishes, in the reverse order of registration. If you open resource A and then resource B that depends on it, B is closed first.
Skipping, filtering and running one group
You can mark a single test or a whole group as skipped by passing the skip argument:
test('upload retries on timeout', () {
// ...
}, skip: 'Waiting for the new upload API');A skipped test is reported but not run. Passing a string records the reason in the output, which is better than skip: true.
To run part of a file, select tests by their full name:
flutter test test/cart_test.dart --plain-name "Cart after adding an item"--plain-name matches tests whose full name contains the given text. --name does the same with a regular expression. Good group names therefore double as filters.
Common mistakes
Other mistakes to watch for:
- Async group bodies. The body passed to
groupmust run synchronously, because the runner uses it to discover which tests exist. Do any async work insidesetUp,setUpAllor the tests themselves. - Order-dependent tests. Tests in one file run in the order they are declared. Code that relies on that order passes locally and fails when you run a single test with
--plain-name. Every test should pass when run alone. - Forgetting that
setUpfailures count. IfsetUpthrows, the test is reported as failed and its body does not run.tearDowncallbacks still run, so write them to cope with objects that were never assigned. Alatevariable that was never initialized throws when read. - Over-sharing setup. If
setUpbuilds ten objects but most tests use two, readers cannot tell what each test depends on. KeepsetUpfor what every test in the group needs. Create anything more specific inside the test or in a nested group. - Hidden global state. Static fields and singletons survive from one test to the next. Reset them in
tearDown. Files run in separate isolates, so state does not leak between files, but it does leak between tests in the same file.
Putting it together
A typical test file for a class has this shape:
- One top-level
groupnamed after the class. - A
latevariable for the object under test, and asetUpthat creates it. - Direct
testcalls for behavior that applies from the initial state. - Nested groups for each meaningful state, each with a small
setUpthat moves the object into that state. tearDownoraddTearDownfor anything that needs closing.
The next chapters build on this structure. Testing asynchronous code and injecting fakes both rely on setUp to create fresh test doubles for each test.
Exercise
A test file contains group('Cart', () { final cart = Cart(); test('a', () { cart.add('x'); }); test('b', () { expect(cart.isEmpty, isTrue); }); });. Test b passes when run alone but fails when the whole file runs. Why, and how do you fix it?
Show answer
The group body runs once at load time, so cart is created once and both tests share it. Test a adds an item first, so test b sees a non-empty cart. Fix it by declaring late Cart cart; in the group body and assigning cart = Cart(); in a setUp, so each test gets a new instance.
Exercise
With one top-level setUp printing "A", a nested group setUp printing "B", a nested tearDown printing "C" and a top-level tearDown printing "D", what is printed around a single test in the nested group?
Show answer
A, B, the test body, C, D. Setups run outermost first, and teardowns run innermost first.