Explain it simply
Explain it simply
A test is a tiny experiment written down: given this input, I expect that output. Without tests you try the program by hand after every change and hope you remember every case. With tests the computer repeats every experiment in seconds, the way a pilot's pre-flight checklist repeats the same checks before every takeoff.
The value is not the first run, when everything passes. It is the hundredth, after a refactor, when one line turns red and tells you exactly which behaviour you just broke.
Problem → Why → Solution
The problem: code checked by eye
Here is how a bug survives when code is checked by eye. average() is run once with [4, 8], prints 6.0, looks right, and ships. Nobody tried the empty list, so the first time a user has no data the program ends with 'Bad state: No element' (reduce has nothing to start from).
The fix is simple, but finding it needed the one case nobody wrote down. Printing and reading output is a test that only works while you are watching, and it only checks what you remember to try.
double average(List<int> values) => values.reduce((a, b) => a + b) / values.length;
void main() {
print(average([4, 8])); // 6.0 - looks right, so we ship it
print(average([])); // found in production: Bad state: No element
}What does a written test change?
A written test makes the expectation explicit and repeatable: 'the average of an empty list is 0.0'. The case runs on every change whether or not anyone remembers it, and a failure names the case. That turns a vague worry into a concrete red line.
Core concept: arrange, act, assert
A test is code that calls your code with a known input and states what must be true afterwards. The shape is always the same: arrange the objects and inputs, act by calling the code once, then assert that the outcome is exactly what you expected. If the assertion fails, the test fails with a message naming the expected and the actual value, and that message is the whole point: it turns 'something feels off' into a precise, repeatable report.
In Dart the standard tool is package:test, a dev dependency. Test files live in test/ and end in _test.dart. Each has a main() in which test(name, body) registers one case, group(name, body) clusters related cases, and expect(actual, matcher) makes the assertion. A matcher can be a plain value, which means equals, or a description such as isEmpty, contains(3) or throwsA(isA<FormatException>()). setUp runs before every test so each case starts from fresh state; cases must never depend on each other or on running order.
| Matcher | Passes when |
|---|---|
| equals(6) (or just 6) | Values match; lists and maps are compared deeply |
| isEmpty | A collection or string has no elements |
| contains(x) | The collection holds x |
| throwsA(isA<FormatException>()) | Calling the function throws that type |
| completion(equals(3)) | The Future completes with 3 |
| emitsInOrder([1, 2]) | The stream emits 1 then 2 |
Choose cases on purpose: a normal case, the boundaries (zero, one, the maximum), empty input, invalid input that must be rejected, and for async code both the success and the failure. Await the Future inside an async test body, or use expectLater with completion and throwsA, so the test cannot finish before the check does. Replace slow or unreliable collaborators (network, clock, files) with a small hand-written fake so the test is fast and gives the same answer every time.
dart test runs every file in test/ and exits with a non-zero code when anything fails, which is what lets CI block a merge. In this lesson package:test cannot be installed, so the worked example builds a tiny test() and expectEqual() from plain Dart; every piece maps one-to-one onto the real API shown in the first deeper section.
- Arrange: prepare objects and input
- Act: call the code under test once
- Assert: expect the exact outcome
- Each case stands alone, with fresh state
Let each test check one behaviour; when it fails, its name alone should tell you what broke.
General pattern
import 'package:test/test.dart';
void main() {
group('subject', () {
setUp(() { /* build fresh objects */ });
test('does X when Y', () {
expect(actualValue, matcher);
});
});
}group collects cases, setUp runs before each one, and every test checks its answer with expect. Name each test as a sentence: what it does, and when.
Checking a shopping cart
The code under test is a Cart class: it adds items, totals the price, applies a discount and has an async checkout. To check it, the example builds a test() in the shape of package:test. test() runs the body and records PASS when it finishes or FAIL when it throws. expectEqual plays the role of expect(actual, equals(expected)) and throws a StateError when the values differ.
The seven cases cover a normal path, a boundary (quantity 0), invalid input (an item not on the menu) and an async failure (checking out an empty cart). At the end, if anything failed, a StateError makes the process exit with a non-zero code, as dart test does. All printing happens in one place at the end, so the output never changes.
import 'dart:async';
class Cart {
final Map<String, int> _prices;
final Map<String, int> _quantities = {};
Cart(this._prices);
void add(String item, int quantity) {
if (!_prices.containsKey(item)) {
throw ArgumentError.value(item, 'item', 'not on the menu');
}
if (quantity < 1) {
throw ArgumentError.value(quantity, 'quantity', 'must be at least 1');
}
_quantities[item] = (_quantities[item] ?? 0) + quantity;
}
int get itemCount => _quantities.values.fold(0, (sum, q) => sum + q);
int totalCents({int percentOff = 0}) {
var gross = 0;
_quantities.forEach((item, quantity) => gross += _prices[item]! * quantity);
return gross - gross * percentOff ~/ 100;
}
Future<String> checkout() async {
await Future.delayed(Duration(milliseconds: 20));
if (itemCount == 0) {
throw StateError('cart is empty');
}
return 'paid ${totalCents()} cents';
}
}
// A tiny stand-in for package:test, built from the same three ideas.
final _report = <String>[];
Future<void> test(String name, FutureOr<void> Function() body) async {
try {
await body();
_report.add('PASS $name');
} catch (e) {
_report.add('FAIL $name: $e');
}
}
void expectEqual(Object? actual, Object? expected) {
if (actual != expected) {
throw StateError('expected $expected but got $actual');
}
}
void expectThrows<T extends Object>(void Function() body) {
try {
body();
} on T {
return;
}
throw StateError('expected $T to be thrown');
}
Future<void> expectThrowsAsync<T extends Object>(Future<void> Function() body) async {
try {
await body();
} on T {
return;
}
throw StateError('expected $T to be thrown');
}
Future<void> main() async {
Cart newCart() => Cart({'tea': 250, 'cake': 400});
await test('empty cart totals zero', () {
expectEqual(newCart().totalCents(), 0);
});
await test('totals quantities times prices', () {
final cart = newCart()..add('tea', 2)..add('cake', 1);
expectEqual(cart.itemCount, 3);
expectEqual(cart.totalCents(), 900);
});
await test('discount is rounded down', () {
final cart = newCart()..add('tea', 1)..add('cake', 1);
expectEqual(cart.totalCents(percentOff: 33), 436);
});
await test('rejects unknown items', () {
expectThrows<ArgumentError>(() => newCart().add('soup', 1));
});
await test('rejects quantity below one', () {
expectThrows<ArgumentError>(() => newCart().add('tea', 0));
});
await test('checkout fails on an empty cart', () async {
await expectThrowsAsync<StateError>(() => newCart().checkout());
});
await test('checkout reports the total', () async {
final cart = newCart()..add('cake', 2);
expectEqual(await cart.checkout(), 'paid 800 cents');
});
_report.forEach(print);
final failed = _report.where((line) => line.startsWith('FAIL')).length;
print('${_report.length - failed} passed, $failed failed');
if (failed > 0) {
throw StateError('$failed test(s) failed');
}
}Code breakdown
- The logic under test
int totalCents({int percentOff = 0}) {Prices are whole cents and the discount is truncated to a whole number with ~/. Code with rounding like this is exactly where tests earn their keep.
- A test runner in miniature
Future<void> test(String name, FutureOr<void> Function() body) async {The body may be sync or async (FutureOr) and is awaited. No exception means PASS; an exception is caught and recorded as FAIL, so one broken case does not stop the others.
- The assertion
void expectEqual(Object? actual, Object? expected) {This is a miniature of expect(actual, equals(expected)). On a mismatch it throws a StateError whose message holds both the expected and the actual value.
- Expecting an exception
} on T {The check passes only if the body throws a T. If nothing is thrown it fails with 'expected T to be thrown'. This mirrors throwsA(isA<T>()).
- An edge case with arithmetic
expectEqual(cart.totalCents(percentOff: 33), 436);The cart holds 650 cents with 33% off. 650 × 33 ~/ 100 is 214 (the 214.5 is truncated), so the customer pays 436. Working the answer out on paper first is the heart of writing a test.
- An async failure
await expectThrowsAsync<StateError>(() => newCart().checkout());Async failures are checked with await too. Without the await, the test could finish before the check does.
- Failing the whole run
throw StateError('$failed test(s) failed');If anything failed the process ends with an error, so a script or CI knows the run failed. The real dart test sets a non-zero exit code in the same situation.
PASS empty cart totals zero
PASS totals quantities times prices
PASS discount is rounded down
PASS rejects unknown items
PASS rejects quantity below one
PASS checkout fails on an empty cart
PASS checkout reports the total
7 passed, 0 failed- Write the expected behaviour as a check
- Run it and watch it fail (red)
- Write the simplest code that passes (green)
- Refactor while the checks stay green
Everything passes
The run ends with exit code 0 and a summary of passed tests.
Something fails
The failing test is named with expected and actual values, and the exit code is non-zero.
The same suite with package:test
In a project that has the package, you write the same cases as shown below. This snippet needs a package called cafe and package:test, so it is not run here as a single file. Notice test() and expect(), and that the Cart is built in setUp so every case gets fresh state.
import 'package:cafe/cart.dart';
import 'package:test/test.dart';
void main() {
late Cart cart;
setUp(() {
cart = Cart({'tea': 250, 'cake': 400});
});
group('Cart', () {
test('empty cart totals zero', () {
expect(cart.totalCents(), 0);
});
test('discount is rounded down', () {
cart.add('tea', 1);
cart.add('cake', 1);
expect(cart.totalCents(percentOff: 33), 436);
});
test('rejects unknown items', () {
expect(() => cart.add('soup', 1), throwsArgumentError);
});
test('checkout fails on an empty cart', () async {
await expectLater(cart.checkout(), throwsStateError);
});
});
}dart pub add --dev test # one-time setup
dart test # every file in test/
dart test test/cart_test.dart # one file
dart test -n 'discount' # only tests whose name matches00:00 +4: All tests passed!The clock time and the number after the plus sign on the last line differ with your machine and your test count. To check a stream, use a matcher such as expect(countdown(3), emitsInOrder([3, 2, 1, emitsDone])); to check a Future, use expectLater(future, completion(equals(3))).
Lists do not compare with ==
In Dart [1, 2] == [1, 2] is false, because lists compare by identity. package:test's expect(list, [1, 2]) and equals compare deeply, but the != inside a hand-written expectEqual does not. That is why this lesson's checkers only compare things with value equality, such as numbers, strings and Duration.
Red, then green
Let us replay the average() bug from the problem section as a test. run() checks two cases: the average of [4, 8] is 6.0 and the average of [] is 0.0. The first version throws on the empty list and reports ERROR, while the corrected version reports PASS. Seeing the test fail first is your proof that it can really catch the bug.
double averageBuggy(List<int> v) => v.reduce((a, b) => a + b) / v.length;
double averageFixed(List<int> v) =>
v.isEmpty ? 0 : v.reduce((a, b) => a + b) / v.length;
String run(String name, double Function(List<int>) average) {
try {
if (average([4, 8]) != 6) return 'FAIL $name: expected 6.0 for [4, 8]';
if (average([]) != 0) return 'FAIL $name: expected 0.0 for []';
return 'PASS $name';
} catch (e) {
return 'ERROR $name: $e';
}
}
void main() {
print(run('averageBuggy', averageBuggy));
print(run('averageFixed', averageFixed));
}ERROR averageBuggy: Bad state: No element
PASS averageFixedReplacing the network with a fake
The Quote class gets each item's price from a PriceApi. In a real app that API calls a server. In a test you hand it a FakePriceApi that implements the same interface, so there is no network, the test is fast, and the answer never changes. The fake also records what it was asked, so you can check that your code calls the API correctly.
abstract class PriceApi {
Future<int> priceOf(String item);
}
class FakePriceApi implements PriceApi {
final Map<String, int> prices;
final List<String> asked = [];
FakePriceApi(this.prices);
@override
Future<int> priceOf(String item) async {
asked.add(item);
final price = prices[item];
if (price == null) throw ArgumentError.value(item, 'item', 'unknown');
return price;
}
}
class Quote {
final PriceApi api;
Quote(this.api);
Future<int> total(List<String> items) async {
var sum = 0;
for (final item in items) {
sum += await api.priceOf(item);
}
return sum;
}
}
void expectEqual(Object? actual, Object? expected) {
if (actual != expected) {
throw StateError('expected $expected but got $actual');
}
}
Future<void> main() async {
final api = FakePriceApi({'tea': 250, 'cake': 400});
final quote = Quote(api);
expectEqual(await quote.total(['tea', 'cake', 'tea']), 900);
expectEqual(api.asked.join(', '), 'tea, cake, tea');
print('quote adds up and asks the API once per item');
try {
await quote.total(['soup']);
throw StateError('expected an ArgumentError');
} on ArgumentError {
print('unknown items fail without any network');
}
}quote adds up and asks the API once per item
unknown items fail without any networkIn real projects
In real projects
Teams run dart test in CI on every change and block the merge when it fails. When a bug is reported, they first write a failing test that reproduces it and only then fix it; that proves the fix works and tells you at once if the bug ever comes back. Flutter follows the same ideas with flutter test and testWidgets.
Coverage can be collected with dart test --coverage, but choosing the right cases matters more than the percentage. Start with hand-written fakes; third-party packages such as mockito or mocktail generate fakes for you, so reach for them when writing fakes by hand becomes tedious. Tests must give the same answer every time, so avoid real network calls, randomness and sleeping.
Common mistakes
Common mistakes
Tests that depend on each other
If you declare a list at the top of the file and two tests call add() on it, whether they pass depends on which one ran first. package:test runs each file in its own isolate, but the tests inside one file share state. Build fresh objects in setUp.
Testing only the happy path
A test that only tries [4, 8] can never catch the empty-list bug in average(). Write separate cases for boundaries such as zero, one and the maximum, for empty input, for invalid input that must be rejected, and for async failures.
Using the real network, clock or randomness
A test that calls a real server and expects an answer within 100 ms fails on the night the server is slow and passes again in the morning. That is a flaky test, and it makes the team stop trusting the suite. Inject a fake, seed any randomness and pass time in as a parameter.
Not awaiting an async check
If a test writes cart.checkout().then((v) { expect(v, ...); }) and neither returns nor awaits the Future, the test can finish before the check runs. A failure may show up late, or go unnoticed. Make the test body async and await, or await expectLater.
Best practices
Best practices
- Name each test as a sentence such as 'discount is rounded down', so a failure explains itself.
- Check one behaviour per test and keep arrange, act and assert visibly separate.
- For every bug, write a failing test first and fix the code second.
- Run dart test in CI, prefer fakes, and keep tests fast and repeatable.
Mini challenge
A duration parser and its checks
Write parseDuration, which turns text such as '1h30m', '45s' or '2h' into a Duration. Then write your own tiny check() and expectEqual() and run six cases: three valid inputs and three that must be rejected. Like a real test runner, one failing check must not stop the rest, and the program fails only at the end.
- parseDuration(text) accepts whole-number parts in the order h, m, s and returns a Duration
- It throws a FormatException for '', '5' (no unit) and '1x' (unknown unit)
- check(name, body) runs the body, prints PASS name on success or FAIL name: message when it throws, and counts failures
- main() runs three valid and three rejected cases, prints 'n passed, m failed' and throws a StateError if any check failed
Duration parseDuration(String text) {
// TODO: accept groups like '1h30m', '45s' or '2h' (units h, m, s in that order)
// TODO: throw FormatException for '', '5' and '1x'
}
void check(String name, void Function() body) {
// TODO: run body; print PASS name, or FAIL name: message when it throws
}
void expectEqual(Object? actual, Object? expected) {
// TODO: throw StateError('expected ... but got ...') when they differ
}
void main() {
// TODO: three checks for valid input (include '90m'), three for rejected input
// TODO: print "<n> passed, <m> failed"; throw StateError when m > 0
}Expected: Six PASS lines (one hour thirty minutes, seconds only, minutes may exceed 59, empty text is rejected, missing unit is rejected, unknown unit is rejected) followed by 6 passed, 0 failed.
Show hint
A regular expression with three optional groups, such as RegExp(r'^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$'), matches every valid shape, but it also matches the empty string, so reject that separately. Duration values compare with ==.
Show solution
Duration parseDuration(String text) {
final match = RegExp(r'^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$').firstMatch(text);
if (text.isEmpty || match == null) {
throw FormatException('not a duration like 1h30m', text);
}
int part(int group) => int.parse(match.group(group) ?? '0');
return Duration(hours: part(1), minutes: part(2), seconds: part(3));
}
var failures = 0;
void expectEqual(Object? actual, Object? expected) {
if (actual != expected) {
throw StateError('expected $expected but got $actual');
}
}
void check(String name, void Function() body) {
try {
body();
print('PASS $name');
} catch (e) {
failures++;
print('FAIL $name: $e');
}
}
void expectRejected(String text) {
try {
parseDuration(text);
} on FormatException {
return;
}
throw StateError('expected "$text" to be rejected');
}
void main() {
check('one hour thirty minutes', () {
expectEqual(parseDuration('1h30m'), Duration(minutes: 90));
});
check('seconds only', () {
expectEqual(parseDuration('45s'), Duration(seconds: 45));
});
check('minutes may exceed 59', () {
expectEqual(parseDuration('90m'), Duration(hours: 1, minutes: 30));
});
check('empty text is rejected', () => expectRejected(''));
check('missing unit is rejected', () => expectRejected('5'));
check('unknown unit is rejected', () => expectRejected('1x'));
print('${6 - failures} passed, $failures failed');
if (failures > 0) {
throw StateError('$failures check(s) failed');
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A test is arrange, act, assert, and a failure is a repeatable report of expected versus actual
- package:test gives you test, group, expect, setUp and matchers, and dart test returns a non-zero exit code so CI can block a merge
- Choose normal, boundary, empty, invalid and async-failure cases on purpose, and await in async tests
- Replace network, time and randomness with fakes; tests must be independent and give the same answer every time
Dart testing — Dart