Sub topic 1
Why test, and which kind of test to write
Prerequisites
You should know basic Dart syntax, including async and await. You should have built simple Flutter apps with stateless and stateful widgets, and you should be comfortable running the flutter command and editing pubspec.yaml.
Why test, and which kind of test to write
Tests catch regressions, which are changes that break behavior that already worked. Flutter has four main test layers:
- Unit tests check one class or function in isolation. They are fast.
- Widget tests build one widget in a test environment and check its behavior.
- Golden tests compare a rendered widget with a stored image.
- Integration tests run the full app on a device or emulator. They are the slowest.
Pick the lowest layer that can prove the behavior. Business logic belongs in unit tests. Layout and tap behavior belong in widget tests.
Setting up and running tests
A new Flutter project already includes flutter_test in its dev dependencies. Put test files in the test/ folder and end each file name with _test.dart. Run every test with this command:
flutter testTo run a single file, pass its path:
flutter test test/counter_test.dartWriting your first unit tests
A unit test uses test() to define one case. expect() compares the actual value with the value you want.
import 'package:flutter_test/flutter_test.dart';
class Counter {
int value = 0;
void increment() => value++;
}
void main() {
test('increment adds one', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
}Grouping tests and sharing setup
group() collects related tests under one label. setUp() runs before each test in the group, so every test starts with a fresh object. Sharing one mutable object across tests is risky, because a change made by one test can make a later test fail.
import 'package:flutter_test/flutter_test.dart';
class Counter {
int value = 0;
void increment() => value++;
}
void main() {
group('Counter', () {
late Counter counter;
setUp(() {
counter = Counter();
});
test('starts at zero', () {
expect(counter.value, 0);
});
test('increment adds one', () {
counter.increment();
expect(counter.value, 1);
});
});
}Exercise
Why does the grouped example create the Counter inside setUp instead of once at the top of main?
Show answer
setUp creates a new Counter before each test, so a change made in one test cannot affect the next test.