Testing with package:test
Automated tests check that your code does what you think — today, and after every future change. Dart's standard testing library is package:test: you describe expectations with test() and expect(), group them, and run them all with dart test.
Note:
package:testneeds the SDK and a project folder, so the test runs on this page are simulated. The runnable examples show the code under test and a tiny hand-madeexpectso you can experiment in the browser.
Setup
dart create already adds test to dev_dependencies. Otherwise:
dart pub add --dev testResolving dependencies...
+ test 1.25.15
Changed 41 dependencies!
Tests live in the test/ folder, in files ending with _test.dart.
A first test
Suppose lib/cart.dart contains:
class Cart {
final _items = <String, int>{}; // name -> price in cents
void add(String name, int priceCents) {
if (priceCents < 0) throw ArgumentError.value(priceCents, 'priceCents');
_items[name] = priceCents;
}
int get total => _items.values.fold(0, (a, b) => a + b);
bool get isEmpty => _items.isEmpty;
}Then test/cart_test.dart could be:
import 'package:shop/cart.dart';
import 'package:test/test.dart';
void main() {
group('Cart', () {
late Cart cart;
setUp(() => cart = Cart()); // fresh cart before every test
test('starts empty', () {
expect(cart.isEmpty, isTrue);
expect(cart.total, 0);
});
test('sums prices', () {
cart
..add('pen', 150)
..add('book', 990);
expect(cart.total, equals(1140));
});
test('rejects negative prices', () {
expect(() => cart.add('bug', -1), throwsArgumentError);
});
});
}dart test00:00 +3: All tests passed!
When something breaks, the runner tells you exactly what was expected and what it got:
dart test00:00 +1 -1: Cart sums prices [E]
Expected: <1140>
Actual: <1040>
package:matcher expect
test/cart_test.dart 18:7 main.<fn>.<fn>
00:00 +2 -1: Some tests failed.
Common matchers
| Matcher | Passes when |
|---|---|
equals(x) (or just x) |
Value == x (deep for collections) |
isTrue, isFalse, isNull, isNotNull |
Self-explanatory |
greaterThan(n), lessThanOrEqualTo(n), closeTo(v, delta) |
Numeric comparisons |
contains(x), isEmpty, hasLength(n) |
Strings and collections |
startsWith('a'), matches(RegExp(...)) |
Strings |
isA<T>() |
Value is a T |
throwsA(isA<FormatException>()), throwsArgumentError |
Function throws |
completion(x), emitsInOrder([...]) |
Futures and streams |
The idea behind expect
expect compares an actual value with a matcher and throws a descriptive error on mismatch. Here's a tiny version you can run right now — the same arrange/act/assert style as real tests:
int passed = 0, failed = 0;
void expectEq(Object? actual, Object? expected, String name) {
if (actual == expected) {
passed++;
print('PASS $name');
} else {
failed++;
print('FAIL $name\n expected: $expected\n actual: $actual');
}
}
String slugify(String title) => title
.toLowerCase()
.trim()
.replaceAll(RegExp(r'[^a-z0-9]+'), '-')
.replaceAll(RegExp(r'^-|-