Testing with package:test
Prerequisites: Packages and pub, Classes and objects
A test is code that checks your other code works. Once written, it runs in a fraction of a second every time you change something, catching mistakes before your users do.
Dart's standard testing library is package:test (Flutter uses
flutter_test, which builds on it). dart create includes it.
The code under test
// lib/cart.dart
class Cart {
final _items = <(String, int)>[];
void add(String name, int price) {
if (price <= 0) throw ArgumentError.value(price, 'price', 'must be positive');
_items.add((name, price));
}
int get total => _items.fold(0, (sum, item) => sum + item.$2);
bool get isEmpty => _items.isEmpty;
}
The tests
// test/cart_test.dart
import 'package:expense_tracker/cart.dart';
import 'package:test/test.dart';
void main() {
group('Cart', () {
late Cart cart;
setUp(() {
cart = Cart();
});
test('starts empty', () {
expect(cart.isEmpty, isTrue);
expect(cart.total, 0);
});
test('total adds up prices', () {
cart.add('book', 12);
cart.add('pen', 3);
expect(cart.total, equals(15));
});
test('rejects non-positive prices', () {
expect(() => cart.add('free', 0), throwsArgumentError);
});
});
}
$ dart test
00:01 +3: All tests passed!
test('description', () { ... })defines a test;grouporganizes related tests.setUpruns before each test, so every test gets a fresh cart.expect(actual, matcher)checks a result. Matchers includeequals,isTrue,isNull,contains,hasLength,throwsA, andthrowsArgumentError.- To check that code throws, pass a function —
() => cart.add(...)— not the call itself.
When a test fails, the output shows Expected: <15> Actual: <12> and
the line number. Editors show a clickable ▶ next to each test.
Async tests
Test bodies can be async: test('loads user', () async { ... }), and
matchers like completion(...) and throwsA(...) work with futures.
Common mistakes
- Writing
expect(cart.add('free', 0), throwsArgumentError)— the exception is thrown beforeexpectruns. Wrap it in() => .... - Tests that depend on the network or on each other. Keep each test self-contained; use fakes for outside services.