Parameterized tests
suggest changeA parameterized (table-driven) test runs the same test logic against many inputs. Instead of copy-pasting a test() call for every case, you describe the cases as data and generate the tests from it.
Some frameworks have a special annotation for this, such as JUnit's @ParameterizedTest or pytest's @pytest.mark.parametrize. Dart's package:test doesn't need one: test() and group() are ordinary functions that you call from main(), so a plain for loop over a list of cases is enough.
This article uses package:test. How to run tests in a CI pipeline is covered in Testing in CI and measuring coverage in Code coverage.
Setup
Add test as a dev dependency:
dart pub add dev:test
The examples test these functions in lib/util.dart:
// lib/util.dart
String slugify(String s) => s
.toLowerCase()
.replaceAll(RegExp(r'[^a-z0-9]+'), '-')
.replaceAll(RegExp(r'^-+|-+$'), '');
Duration parseDuration(String s) {
final m = RegExp(r'^(\d+)([smh])$').firstMatch(s);
if (m == null) throw FormatException('invalid duration', s);
final n = int.parse(m[1]!);
return switch (m[2]) {
's' => Duration(seconds: n),
'm' => Duration(minutes: n),
'h' => Duration(hours: n),
_ => throw StateError('unreachable'),
};
}
bool isLeapYear(int year) =>
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
Test files go in test/ and their names must end with _test.dart.
The problem: one test, many asserts
The easiest way to check many inputs is a loop inside a single test:
import 'package:test/test.dart';
import 'package:myapp/util.dart';
void main() {
test('slugify', () {
expect(slugify('Hello World'), 'hello-world');
expect(slugify(' Dart 3 is out! '), 'dart-3-is-out');
expect(slugify('already-a-slug'), 'already-a-slug');
expect(slugify(''), '');
});
}
This works, but it has two problems:
- The first failing
expectthrows and ends the test, so you never find out whether the later cases pass. - The report shows one test called
slugify. You have to read the stack trace to work out which input failed.
A parameterized test fixes both: each case becomes its own test, with its own name and its own pass/fail result.
A loop of test() calls
Put the cases in a list of records and call test() once for each:
import 'package:test/test.dart';
import 'package:myapp/util.dart';
void main() {
const cases = [
(input: 'Hello World', expected: 'hello-world'),
(input: ' Dart 3 is out! ', expected: 'dart-3-is-out'),
(input: 'already-a-slug', expected: 'already-a-slug'),
(input: 'C++ & Rust', expected: 'c-rust'),
(input: '', expected: ''),
];
group('slugify', () {
for (final (:input, :expected) in cases) {
test('"$input" -> "$expected"', () {
expect(slugify(input), expected);
});
}
});
}
for (final (:input, :expected) in cases) uses a record pattern to pull both fields into local variables. The :input shorthand means "bind the field input to a variable named input".
Run it with the expanded reporter to see one line per test:
dart test test/slugify_test.dart -r expanded
Output:
00:00 +0: loading test/slugify_test.dart
00:00 +0: slugify "Hello World" -> "hello-world"
00:00 +1: slugify " Dart 3 is out! " -> "dart-3-is-out"
00:00 +2: slugify "already-a-slug" -> "already-a-slug"
00:00 +3: slugify "C++ & Rust" -> "c-rust"
00:00 +4: slugify "" -> ""
00:00 +5: All tests passed!
The group name is prepended to each test name, so the full name of the first test is slugify "Hello World" -> "hello-world".
Why the closure captures the right value
Each closure passed to test() runs later, after main() has finished declaring all tests. In some languages that's a classic bug: every closure would see the last value of the loop variable.
Dart creates a fresh variable for every iteration, both in for-in loops and in C-style for (var i = 0; ...) loops, so each closure captures its own input and expected. No extra copy is needed.
Naming the test cases
Every test should have a unique, readable name. Interpolating the input and expected value, as above, is usually enough. When inputs are long or not printable, add an explicit description:
const cases = [
(name: 'two words', input: 'Hello World', expected: 'hello-world'),
(name: 'trims punctuation', input: '!!hi!!', expected: 'hi'),
(name: 'collapses runs', input: 'a -- b', expected: 'a-b'),
(name: 'empty string', input: '', expected: ''),
];
for (final c in cases) {
test(c.name, () => expect(slugify(c.input), c.expected));
}
If the list has no natural names, Iterable.indexed gives you a case number:
for (final (i, (:input, :expected)) in cases.indexed) {
test('case #$i: $input', () => expect(slugify(input), expected));
}
Avoid duplicate names. They make reports confusing and make it impossible to select one specific case with --plain-name (see below).
Testing exceptions
Error cases are data too. A separate table for invalid input keeps both tables simple:
import 'package:test/test.dart';
import 'package:myapp/util.dart';
void main() {
group('parseDuration', () {
const valid = [
(input: '90s', expected: Duration(seconds: 90)),
(input: '5m', expected: Duration(minutes: 5)),
(input: '2h', expected: Duration(hours: 2)),
(input: '0s', expected: Duration.zero),
];
for (final (:input, :expected) in valid) {
test('parses "$input"', () {
expect(parseDuration(input), expected);
});
}
const invalid = ['', 'abc', '10', '10x', '-5s', '1.5h', ' 5m'];
for (final input in invalid) {
test('rejects "$input"', () {
expect(() => parseDuration(input), throwsFormatException);
});
}
});
}
Output:
00:00 +0: loading test/duration_test.dart
00:00 +0: parseDuration parses "90s"
00:00 +1: parseDuration parses "5m"
00:00 +2: parseDuration parses "2h"
00:00 +3: parseDuration parses "0s"
00:00 +4: parseDuration rejects ""
00:00 +5: parseDuration rejects "abc"
00:00 +6: parseDuration rejects "10"
00:00 +7: parseDuration rejects "10x"
00:00 +8: parseDuration rejects "-5s"
00:00 +9: parseDuration rejects "1.5h"
00:00 +10: parseDuration rejects " 5m"
00:00 +11: All tests passed!
Duration has a const constructor and implements ==, so it works both in a const list and as an expect value.
Matchers as expected values
The second argument of expect can be a plain value or a Matcher. Because of that, a single table can mix exact values with looser checks. Type the field as Object? so it accepts both:
import 'dart:math' as math;
import 'package:test/test.dart';
void main() {
final cases = <({String name, Object? Function() compute, Object? matcher})>[
(name: 'exact int', compute: () => 6 * 7, matcher: 42),
(name: 'float', compute: () => 1 / 3, matcher: closeTo(0.333, 0.001)),
(name: 'sqrt', compute: () => math.sqrt(2), matcher: inInclusiveRange(1.41, 1.42)),
(name: 'list', compute: () => [3, 1, 2]..sort(), matcher: orderedEquals([1, 2, 3])),
(name: 'string', compute: () => 'Hello, Dart', matcher: allOf(startsWith('Hello'), contains('Dart'))),
];
for (final c in cases) {
test(c.name, () => expect(c.compute(), c.matcher));
}
}
A plain value like 42 is wrapped in equals(42) automatically. Don't put throwsA-style matchers in this table: they must receive the function itself, not its result. Keep error cases in their own table, as in the previous section, rather than branching inside the test body.
Expected value per input: maps
When each case is just "input maps to output", a Map literal is a compact table:
import 'package:test/test.dart';
import 'package:myapp/util.dart';
void main() {
const leapYears = {
1900: false, // divisible by 100 but not by 400
2000: true, // divisible by 400
2023: false,
2024: true,
2100: false,
};
group('isLeapYear', () {
leapYears.forEach((year, expected) {
test('$year -> $expected', () => expect(isLeapYear(year), expected));
});
});
}
Map keys must be unique, which protects you from accidentally duplicating a case. Use a list of records when you need more than two fields, or when inputs repeat.
Skipping and tagging individual cases
Every parameter of test() can come from the table. A common use is skipping a known failure without deleting the case:
const cases = [
(input: 'Hello World', expected: 'hello-world', skip: null),
(input: 'Ünïcode', expected: 'unicode', skip: 'transliteration not implemented'),
];
for (final c in cases) {
test('"${c.input}"', () {
expect(slugify(c.input), c.expected);
}, skip: c.skip);
}
Output:
00:00 +0: loading test/slugify_test.dart
00:00 +0: "Hello World"
00:00 +1: "Ünïcode"
Skip: transliteration not implemented
00:00 +1 ~1: All tests passed!
skip accepts null or false (run the test), true (skip), or a String (skip, with the string as the reason).
Tags work the same way. Mark slow cases and exclude them during local development:
for (final size in [10, 1000, 1000000]) {
test('sorts $size items', () {
final list = List.generate(size, (i) => size - i)..sort();
expect(list.first, 1);
expect(list.last, size);
}, tags: size > 1000 ? ['slow'] : null);
}
dart test -x slow # exclude tests tagged "slow"
dart test -t slow # run only tests tagged "slow"
Declare tags in dart_test.yaml at the package root, otherwise dart test prints a warning about undeclared tags:
tags:
slow:
timeout: 2x
Running a single case
Because every case is a separate test with its own name, you can run just one of them. --plain-name (-N) matches a substring of the full name, --name (-n) matches a regular expression:
dart test test/duration_test.dart -N 'rejects "10x"'
dart test test/duration_test.dart -n 'parseDuration parses "\d+m"'
Output of the first command:
00:00 +0: parseDuration rejects "10x"
00:00 +1: All tests passed!
This is the main practical advantage over a loop inside one test: when one case of hundreds fails, you rerun only that one while debugging it.
Reading what failed
When a case fails, the test name tells you which input broke. Suppose you add a case with the wrong expectation:
(input: 'a_b', expected: 'a_b'),
Output:
00:00 +5: slugify "a_b" -> "a_b"
00:00 +5 -1: slugify "a_b" -> "a_b" [E]
Expected: 'a_b'
Actual: 'a-b'
Which: is different.
Expected: a_b
Actual: a-b
^
Differ at offset 1
package:matcher expect
test/slugify_test.dart 17:9 main.<fn>.<fn>
00:00 +5 -1: Some tests failed.
The other cases still run and pass. With the single-test approach, every case after the broken one would have been skipped.
For extra context in the failure message, pass reason:
expect(slugify(input), expected, reason: 'input bytes: ${input.codeUnits}');
Async test cases
Test bodies can be async. The loop itself must stay synchronous, because all tests have to be declared before any of them runs:
import 'dart:io';
import 'package:test/test.dart';
Future<int> fileLength(String path) async => (await File(path).readAsBytes()).length;
void main() {
late Directory dir;
setUpAll(() async {
dir = await Directory.systemTemp.createTemp('lengths');
});
tearDownAll(() => dir.delete(recursive: true));
const cases = [
(content: '', length: 0),
(content: 'abc', length: 3),
(content: 'zażółć', length: 10), // UTF-8: 4 non-ASCII chars x 2 bytes
];
for (final (:content, :length) in cases) {
test('"$content" is $length bytes', () async {
final file = File('${dir.path}/f.txt');
await file.writeAsString(content);
expect(await fileLength(file.path), length);
});
}
}
Note that dir is assigned in setUpAll and used only inside the test bodies. Code directly in the loop runs at declaration time, before setUpAll, so it can't use dir.
Loading cases from a file
Large tables, or tables shared with other languages, can live in a JSON fixture:
[
{"input": "Hello World", "expected": "hello-world"},
{"input": " Dart 3 is out! ", "expected": "dart-3-is-out"},
{"input": "C++ & Rust", "expected": "c-rust"}
]
Read it synchronously at the top of main():
import 'dart:convert';
import 'dart:io';
import 'package:test/test.dart';
import 'package:myapp/util.dart';
void main() {
final raw = File('test/fixtures/slugify.json').readAsStringSync();
final cases = (jsonDecode(raw) as List).cast<Map<String, dynamic>>();
group('slugify (fixture)', () {
for (final c in cases) {
final input = c['input'] as String;
final expected = c['expected'] as String;
test('"$input"', () => expect(slugify(input), expected));
}
});
}
dart test runs with the package root as the working directory, so paths like test/fixtures/... resolve correctly. The synchronous read is intentional: test declaration can't wait for a Future. See JSON for more on decoding.
Combinations of parameters
Nested loops generate the cross product of several parameter lists. This is useful when a function should behave the same way for every combination:
import 'package:test/test.dart';
String pad(String s, int width, {required bool left}) =>
left ? s.padLeft(width) : s.padRight(width);
void main() {
const inputs = ['', 'a', 'hello'];
const widths = [0, 3, 8];
const sides = [true, false];
for (final s in inputs) {
for (final w in widths) {
for (final left in sides) {
test('pad("$s", $w, left: $left)', () {
final result = pad(s, w, left: left);
expect(result.length, s.length > w ? s.length : w);
expect(result.trim(), s);
});
}
}
}
}
This declares 3 x 3 x 2 = 18 tests. Check properties that hold for every combination (here: the length and the trimmed content) instead of listing 18 expected strings by hand.
Randomized cases with a fixed seed
You can also generate inputs. Always use a seeded Random, so the same tests are generated on every run and a failure can be reproduced:
import 'dart:math';
import 'package:test/test.dart';
void main() {
final rng = Random(42);
final inputs = List.generate(20, (_) => rng.nextInt(1 << 31) - (1 << 30));
group('int round-trip', () {
for (final n in inputs) {
test('$n', () {
expect(int.parse(n.toString()), n);
expect(int.parse(n.toRadixString(16), radix: 16), n);
});
}
});
}
The input value is part of the test name, so a failing case can be copied straight into a hand-written table as a regression test.
Tips
- Declare tests synchronously, directly in
main()or in agroup()callback. Callingtest()inside asetUp, a test body, or after anawaitis an error. - Keep the test body small and identical for every case. If you need
ifstatements to handle different kinds of cases, split them into separate tables. - Prefer
constlists of records. They're type-checked, immutable, and the analyzer reports a missing or misspelled field. - Put the input in the test name. A failure report should say which case failed without opening the source.
- Use
group()to give a table a common prefix, sodart test -N 'parseDuration'runs all its cases.