Sub topic 3
Writing Your First Unit Tests
Prerequisites and the unit-test model
This chapter assumes you know basic Dart syntax, classes, and async and await, and that you can run the flutter command-line tool. A unit test checks one small piece of Dart code without building a widget or launching an app. The code under test is usually a function or class.
A good unit test has three parts:
- Arrange the inputs and starting state.
- Act by calling the code under test.
- Assert that the result matches the expected behavior.
Flutter projects include the flutter_test package, which provides the test functions and matchers used in this chapter. A matcher is an object that describes an expected value, such as 0, isTrue, or findsOneWidget.
Create a test file
Put unit tests in the test directory. By convention, a test file ends in _test.dart, such as test/counter_test.dart.
The following example defines a small Counter class and checks its initial value and increment behavior:
import 'package:flutter_test/flutter_test.dart';
class Counter {
int value = 0;
void increment() {
value++;
}
}
void main() {
test('a new counter starts at zero', () {
final counter = Counter();
expect(counter.value, 0);
});
test('increment increases the value by one', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
}The main function registers the tests. Each test call receives a description and a callback. The callback contains the steps for one behavior. expect compares an actual value with an expected value. If the comparison fails, Flutter reports the test description, the actual value, and the expected value.
Run every test from the project root:
flutter testRun only this file when developing it:
flutter test test/counter_test.dartCommon errors
A test can pass for the wrong reason if it does not exercise the behavior it claims to check. For example, a test that only asserts the initial value does not prove that increment works. Keep the action and assertion visibly connected.
Create a fresh object inside each test. Shared mutable objects can carry state from one test into another, making the result depend on test order. Later, setUp can remove repeated initialization while still creating isolated state for each test.
Choose expectations that describe the contract. If a method should return a name, assert the name. Avoid asserting incidental details such as the current order of private helper calls unless that order is part of the public behavior.
Exercise
What should you assert after calling counter.increment() on a new Counter?
Show answer
Assert that counter.value equals 1, because that is the observable behavior promised by increment.