Unit testing

suggest change

A unit test checks one small piece of code, usually a function or a class, in isolation. It calls the code with known inputs and asserts that the result is what you expect. Good unit tests run in milliseconds, so you can run all of them after every change.

The standard tool in Dart is package:test. It gives you:

This article covers the fundamentals. Related topics have their own articles:

Setup

dart create already adds package:test to a new project. For an existing project, add it as a dev dependency:

dart pub add dev:test

This adds it under dev_dependencies in pubspec.yaml, because tests are not part of the code you ship:

dev_dependencies:
  lints: ^6.0.0
  test: ^1.33.0

By convention, the code under test lives in lib/ and the tests live in test/. The runner only picks up files whose names end with _test.dart. A common layout mirrors lib/:

myapp/
  pubspec.yaml
  lib/
    myapp.dart
    cart.dart
    text.dart
  test/
    cart_test.dart
    text_test.dart

Tests import your code through its package name (package:myapp/...), just like any other user of the library.

Code under test

The examples in this article test these two files.

// lib/text.dart
String capitalize(String s) =>
    s.isEmpty ? s : s[0].toUpperCase() + s.substring(1);

int wordCount(String s) =>
    s.trim().isEmpty ? 0 : s.trim().split(RegExp(r'\s+')).length;
// lib/cart.dart
class Item {
  final String name;
  final double price;
  const Item(this.name, this.price);

  @override
  bool operator ==(Object other) =>
      other is Item && other.name == name && other.price == price;

  @override
  int get hashCode => Object.hash(name, price);

  @override
  String toString() => 'Item($name, $price)';
}

class Cart {
  final _items = <Item, int>{};

  void add(Item item, {int quantity = 1}) {
    if (quantity <= 0) {
      throw ArgumentError.value(quantity, 'quantity', 'must be positive');
    }
    _items.update(item, (q) => q + quantity, ifAbsent: () => quantity);
  }

  void remove(Item item) {
    if (_items.remove(item) == null) {
      throw StateError('${item.name} is not in the cart');
    }
  }

  int get count => _items.values.fold(0, (a, b) => a + b);

  double get total =>
      _items.entries.fold(0.0, (sum, e) => sum + e.key.price * e.value);

  List<Item> get items => _items.keys.toList();

  bool get isEmpty => _items.isEmpty;
}

lib/myapp.dart re-exports both with export 'cart.dart'; and export 'text.dart';.

Your first test

A test file is a Dart program with a main() function. Inside main() you call test() with a description and a function that contains the checks:

// test/text_test.dart
import 'package:myapp/myapp.dart';
import 'package:test/test.dart';

void main() {
  test('capitalize upper-cases the first letter', () {
    expect(capitalize('dart'), 'Dart');
  });

  test('capitalize leaves an empty string alone', () {
    expect(capitalize(''), '');
  });

  test('wordCount counts words separated by whitespace', () {
    expect(wordCount('  unit   testing\tin dart '), 4);
  });
}

expect(actual, matcher) is the assertion. If the second argument is a plain value, it is wrapped in equals(), so expect(x, 'Dart') means "x must equal 'Dart'".

Run every test in test/ from the project root:

dart test

Output:

00:00 +0: loading test/text_test.dart
00:00 +0: test/text_test.dart: capitalize upper-cases the first letter
00:00 +1: test/text_test.dart: capitalize leaves an empty string alone
00:00 +2: test/text_test.dart: wordCount counts words separated by whitespace
00:00 +3: All tests passed!

+3 is the number of passed tests. Failures are shown as -N and skipped tests as ~N. The process exits with code 0 only if every test passed, which is what CI systems check.

You can also run a single file, or a directory:

dart test test/text_test.dart
dart test test/models/

Reading a failure

When an expectation fails, expect throws a TestFailure. The test stops at that line and the runner prints what was expected, what it got, and where:

import 'package:myapp/myapp.dart';
import 'package:test/test.dart';

void main() {
  test('capitalize handles a leading space', () {
    expect(capitalize(' dart'), 'Dart');
  });

  test('word lists', () {
    expect('a b c'.split(' '), ['a', 'b', 'd']);
  });

  test('reason', () {
    final cart = Cart()..add(const Item('pen', 1.5), quantity: 2);
    expect(cart.count, 3, reason: 'two pens were added');
  });
}

Output:

00:00 +0: loading test/fail_test.dart
00:00 +0: capitalize handles a leading space
00:00 +0 -1: capitalize handles a leading space [E]
  Expected: 'Dart'
    Actual: ' dart'
     Which: is different.
            Expected: Dart
              Actual:  dart
                      ^
             Differ at offset 0
  
  package:matcher          expect
  test/fail_test.dart 6:5  main.<fn>
  
00:00 +0 -1: word lists
00:00 +0 -2: word lists [E]
  Expected: ['a', 'b', 'd']
    Actual: ['a', 'b', 'c']
     Which: at location [2] is 'c' instead of 'd'
  
  package:matcher           expect
  test/fail_test.dart 10:5  main.<fn>
  
00:00 +0 -2: reason
00:00 +0 -3: reason [E]
  Expected: <3>
    Actual: <2>
  two pens were added
  
  package:matcher           expect
  test/fail_test.dart 15:5  main.<fn>
  
00:00 +0 -3: Some tests failed.

Failing tests:
  test/fail_test.dart: capitalize handles a leading space
  test/fail_test.dart: reason
  test/fail_test.dart: word lists

Notice the Which: lines: matchers explain why a value didn't match, such as the offset of the first differing character or the index of the wrong list element. The optional reason: argument adds your own message to the report.

Note that a failure in one test doesn't stop the others: every test runs and the summary lists all failures.

Matchers

A matcher describes what a value should look like. Using a specific matcher instead of expect(condition, isTrue) produces much better failure messages. Here are the ones you'll use most, all from package:test (they come from package:matcher, which package:test re-exports):

import 'package:myapp/myapp.dart';
import 'package:test/test.dart';

void main() {
  test('equality and identity', () {
    expect(1 + 1, 2); // same as equals(2)
    expect(1 + 1, equals(2));
    expect([1, 2, 3], [1, 2, 3]); // deep equality for lists
    expect({'a': 1, 'b': [2, 3]}, {'b': [2, 3], 'a': 1});
    expect(const Item('pen', 1.5), const Item('pen', 1.5)); // uses ==
    final cart = Cart();
    expect(cart, same(cart));
  });

  test('booleans and null', () {
    expect(''.isEmpty, isTrue);
    expect([1].isEmpty, isFalse);
    expect(int.tryParse('x'), isNull);
    expect(int.tryParse('42'), isNotNull);
  });

  test('numbers', () {
    expect(10, greaterThan(5));
    expect(10, lessThanOrEqualTo(10));
    expect(10, inInclusiveRange(1, 10));
    expect(0.1 + 0.2, closeTo(0.3, 1e-9));
    expect(-3, isNegative);
  });

  test('strings', () {
    const s = 'Hello, Dart world';
    expect(s, startsWith('Hello'));
    expect(s, endsWith('world'));
    expect(s, contains('Dart'));
    expect(s, matches(RegExp(r'^\w+, \w+')));
    expect('  DART ', equalsIgnoringWhitespace('DART'));
    expect('DaRt', equalsIgnoringCase('dart'));
    expect(s, stringContainsInOrder(['Hello', 'Dart', 'world']));
  });

  test('collections', () {
    final xs = [3, 1, 2];
    expect(xs, hasLength(3));
    expect(xs, contains(2));
    expect(xs, isNot(contains(7)));
    expect(xs, unorderedEquals([1, 2, 3]));
    expect(xs, containsAll([1, 3]));
    expect(xs, everyElement(isPositive));
    expect(xs, anyElement(greaterThan(2)));
    expect([], isEmpty);
    expect({'id': 7, 'name': 'Ann'}, containsPair('name', 'Ann'));
    expect({'id': 7}, contains('id')); // checks keys
  });

  test('types and combinations', () {
    Object value = 42;
    expect(value, isA<int>());
    expect(value, allOf(isA<int>(), greaterThan(40), lessThan(50)));
    expect(value, anyOf(0, 42, 100));
    expect(value, predicate<int>((n) => n.isEven, 'is even'));
  });
}

All 6 tests pass. A few things worth knowing:

Checking several properties with having

isA<T>().having(feature, description, matcher) checks a property of an object. You can chain as many having calls as you like:

test('having on a value', () {
  final cart = Cart()..add(const Item('pen', 1.5), quantity: 2);
  expect(
    cart,
    isA<Cart>()
        .having((c) => c.count, 'count', 2)
        .having((c) => c.isEmpty, 'isEmpty', isFalse)
        .having((c) => c.items.single.name, 'item name', 'pen'),
  );
});

Compared to three separate expect calls, the failure message describes the whole object and names the property that didn't match.

Writing a custom matcher

When the same check appears in many tests, wrap it in a matcher. The easiest base class is CustomMatcher: you say how to extract a feature from the actual value, and pass a matcher for that feature:

class _HasTotal extends CustomMatcher {
  _HasTotal(Object? matcher) : super('Cart with total', 'total', matcher);

  @override
  Object? featureValueOf(dynamic actual) => (actual as Cart).total;
}

Matcher hasTotal(Object? matcher) => _HasTotal(matcher);

void main() {
  test('custom matcher', () {
    final cart = Cart()..add(const Item('pen', 1.5), quantity: 2);
    expect(cart, hasTotal(3.0));
    expect(cart, hasTotal(greaterThan(2)));
  });

  test('custom matcher failure', () {
    final cart = Cart()..add(const Item('pen', 1.5));
    expect(cart, hasTotal(10));
  });
}

The failing test reports:

  Expected: Cart with total <10>
    Actual: <Instance of 'Cart'>
     Which: has total with value <1.5>

Testing exceptions

To check that code throws, pass a function to expect, not the result of calling it. If you write expect(cart.remove(pen), throwsStateError), the exception is thrown while evaluating the argument, before expect even runs, and the test fails with that exception.

There are ready-made matchers for common error types: throwsArgumentError, throwsStateError, throwsFormatException, throwsRangeError, throwsUnsupportedError, throwsNoSuchMethodError and a few more. For anything else, use throwsA(matcher):

test('FormatException from int.parse', () {
  expect(() => int.parse('abc'), throwsFormatException);
  expect(() => int.parse('abc'), throwsA(isA<FormatException>()));
});

Combine throwsA with having to check the fields of the exception:

test('exception type and fields', () {
  final cart = Cart();
  expect(
    () => cart.add(const Item('pen', 1.5), quantity: -1),
    throwsA(
      isA<ArgumentError>()
          .having((e) => e.name, 'name', 'quantity')
          .having((e) => e.invalidValue, 'invalidValue', -1)
          .having((e) => e.message, 'message', contains('positive')),
    ),
  );
});

If the exception is thrown but a field is wrong, the report shows both the exception and the mismatch:

test('wrong field fails', () {
  expect(
    () => Cart().remove(const Item('pen', 1.5)),
    throwsA(isA<StateError>().having((e) => e.message, 'message', 'gone')),
  );
});
  Expected: throws <Instance of 'StateError'> with `message`: 'gone'
    Actual: <Closure: () => void>
     Which: threw StateError:<Bad state: pen is not in the cart>
            stack package:myapp/cart.dart 29:7     Cart.remove
                  test/exceptions_test.dart 38:20  main.<fn>.<fn>
                  package:matcher                  expect
                  test/exceptions_test.dart 37:5   main.<fn>
                  
            which has `message` with value 'pen is not in the cart' which is different.
                  Expected: gone
                    Actual: pen is not ...
                            ^
                   Differ at offset 0

You can also use a plain try/catch with fail(), which fails the test with a message. It's more verbose, but sometimes easier when you need several checks on the caught exception:

test('try/catch style', () {
  try {
    Cart().remove(const Item('pen', 1.5));
    fail('expected StateError');
  } on StateError catch (e) {
    expect(e.message, 'pen is not in the cart');
  }
});

The opposite check is returnsNormally:

expect(() => Cart().add(const Item('pen', 1.5)), returnsNormally);

See Exceptions and Custom exception for how to design the exceptions you test for.

Organizing tests with group

group() collects related tests under a common description. Groups can be nested, and the group descriptions are prepended to test names in the output and in filters:

// test/cart_test.dart
import 'package:myapp/myapp.dart';
import 'package:test/test.dart';

void main() {
  const pen = Item('pen', 1.5);
  const book = Item('book', 12.0);

  late Cart cart;

  setUp(() {
    cart = Cart(); // a fresh cart for every test
  });

  group('add', () {
    test('a new item', () {
      cart.add(pen);
      expect(cart.items, [pen]);
      expect(cart.count, 1);
    });

    test('the same item twice increases quantity', () {
      cart.add(pen);
      cart.add(pen, quantity: 2);
      expect(cart.items, [pen]);
      expect(cart.count, 3);
    });

    test('rejects a non-positive quantity', () {
      expect(() => cart.add(pen, quantity: 0), throwsArgumentError);
    });
  });

  group('remove', () {
    setUp(() {
      cart.add(pen);
      cart.add(book);
    });

    test('an item in the cart', () {
      cart.remove(pen);
      expect(cart.items, [book]);
    });

    test('an unknown item throws StateError', () {
      cart.remove(pen);
      expect(() => cart.remove(pen), throwsStateError);
    });
  });

  test('total sums price times quantity', () {
    cart
      ..add(pen, quantity: 4)
      ..add(book);
    expect(cart.total, closeTo(18.0, 0.001));
  });
}

Output:

00:00 +0: loading test/cart_test.dart
00:00 +0: add a new item
00:00 +1: add the same item twice increases quantity
00:00 +2: add rejects a non-positive quantity
00:00 +3: remove an item in the cart
00:00 +4: remove an unknown item throws StateError
00:00 +5: total sums price times quantity
00:00 +6: All tests passed!

Writing descriptions so that "group + test" reads as a sentence ("remove an unknown item throws StateError") makes failure reports self-explanatory.

test() and group() are ordinary function calls that run when main() runs. The test bodies run later, after all tests have been declared. Don't do real work directly inside a group() callback; put it in setUp or in the test itself.

setUp, tearDown and friends

Tests must not depend on each other or on the order in which they run. The usual way to guarantee that is to build fresh state before each test:

This program prints the order in which everything runs:

import 'package:test/test.dart';

void main() {
  setUpAll(() => print('setUpAll'));
  tearDownAll(() => print('tearDownAll'));
  setUp(() => print('  setUp'));
  tearDown(() => print('  tearDown'));

  test('first', () => print('    first'));

  group('inner', () {
    setUp(() => print('    inner setUp'));
    tearDown(() => print('    inner tearDown'));

    test('second', () {
      print('      second');
      addTearDown(() => print('      addTearDown from second'));
    });
  });
}

Output:

00:00 +0: loading test/lifecycle_test.dart
00:00 +0: (setUpAll)
setUpAll
00:00 +0: first
  setUp
    first
  tearDown
00:00 +1: inner second
  setUp
    inner setUp
      second
      addTearDown from second
    inner tearDown
  tearDown
00:00 +2: (tearDownAll)
tearDownAll
00:00 +2: All tests passed!

Outer setUp runs before inner setUp, and teardowns run in reverse order. addTearDown callbacks run first, in reverse order of registration.

The late Cart cart; + setUp pattern in cart_test.dart is idiomatic. Avoid initializing mutable state once at the top of main() (final cart = Cart();): every test would share the same cart, and a test that adds an item would break the next one.

Testing asynchronous code

Make the test function async and await the code under test. The runner waits for the returned Future to complete before it considers the test done. Hooks can be async too.

Here is an async function that reads a file:

// lib/files.dart
import 'dart:io';

import 'text.dart';

Future<int> countWordsInFile(String path) async {
  final file = File(path);
  if (!await file.exists()) {
    throw FileSystemException('no such file', path);
  }
  return wordCount(await file.readAsString());
}

The tests create a private temporary directory for each test and delete it afterwards, so they never touch real files and can run in parallel (see Temporary files). They use package:path, added with dart pub add dev:path:

// test/files_test.dart
import 'dart:io';

import 'package:myapp/myapp.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';

void main() {
  late Directory tmp;

  setUp(() async {
    tmp = await Directory.systemTemp.createTemp('myapp_test_');
  });

  tearDown(() async {
    await tmp.delete(recursive: true);
  });

  test('counts words in a file', () async {
    final path = p.join(tmp.path, 'notes.txt');
    await File(path).writeAsString('one two\nthree');

    final n = await countWordsInFile(path);

    expect(n, 3);
  });

  test('a missing file throws FileSystemException', () async {
    final path = p.join(tmp.path, 'missing.txt');
    await expectLater(
      countWordsInFile(path),
      throwsA(isA<FileSystemException>()),
    );
  });

  test('completion matcher', () {
    final path = p.join(tmp.path, 'empty.txt');
    File(path).writeAsStringSync('');
    return expectLater(countWordsInFile(path), completion(0));
  });
}

Output:

00:00 +0: loading test/files_test.dart
00:00 +0: counts words in a file
00:00 +1: a missing file throws FileSystemException
00:00 +2: completion matcher
00:00 +3: All tests passed!

Points to note:

The forgotten await

The most common async testing bug is starting async work without waiting for it. The test function returns immediately, the runner marks it as passed, and the assertion runs later:

import 'package:test/test.dart';

Future<int> slowAnswer() async {
  await Future<void>.delayed(const Duration(milliseconds: 50));
  return 42;
}

void main() {
  test('BUG: result is checked after the test has finished', () {
    slowAnswer().then((n) => expect(n, 0));
  });

  test('fixed: await the future', () async {
    expect(await slowAnswer(), 42);
  });
}

Output:

00:00 +0: loading test/x_test.dart
00:00 +0: BUG: result is checked after the test has finished
00:00 +1: fixed: await the future
00:00 +0 -1: fixed: await the future
00:00 +0 -1: BUG: result is checked after the test has finished [E]
  Expected: <0>
    Actual: <42>
  
  package:matcher         expect
  test/x_test.dart 10:30  main.<fn>.<fn>
  
00:00 +0 -1: fixed: await the future
00:00 +0 -1: BUG: result is checked after the test has finished [E]
  This test failed after it had already completed.
  Make sure to use a matching library which informs the test runner
  of pending async work.
  package:matcher         expect
  test/x_test.dart 10:30  main.<fn>.<fn>

Here the runner happened to notice, because the error arrived while the file was still running. If the late failure arrives after the whole suite has finished, it can be lost entirely. Always make the test async and await futures, or use expectLater. Enabling the unawaited_futures lint in analysis_options.yaml catches many of these mistakes.

Testing streams

Stream matchers check the sequence of events a stream emits. Here is a stream to test:

// lib/files.dart (continued)
Stream<int> countdown(int from) async* {
  if (from < 0) throw RangeError.value(from, 'from');
  for (var i = from; i > 0; i--) {
    await Future<void>.delayed(const Duration(milliseconds: 10));
    yield i;
  }
}
// test/stream_test.dart
import 'dart:async';

import 'package:myapp/myapp.dart';
import 'package:test/test.dart';

void main() {
  test('countdown emits values then closes', () {
    expect(countdown(3), emitsInOrder([3, 2, 1, emitsDone]));
  });

  test('collect to a list', () async {
    expect(await countdown(3).toList(), [3, 2, 1]);
  });

  test('negative start emits an error', () {
    expect(countdown(-1), emitsError(isRangeError));
  });

  test('emitsThrough skips uninteresting events', () async {
    final controller = StreamController<String>();
    final done = expectLater(
      controller.stream,
      emitsInOrder([
        'start',
        emitsThrough('ready'),
        mayEmit('debug'),
        'stop',
        emitsDone,
      ]),
    );
    controller
      ..add('start')
      ..add('loading')
      ..add('ready')
      ..add('stop');
    await controller.close();
    await done;
  });
}

Output:

00:00 +0: loading test/stream_test.dart
00:00 +0: countdown emits values then closes
00:00 +1: collect to a list
00:00 +2: negative start emits an error
00:00 +3: emitsThrough skips uninteresting events
00:00 +4: All tests passed!

The main stream matchers are:

Matcher Meaning
emits(m) the next event matches m (a plain value works too)
emitsInOrder([...]) the next events match the list, in order
emitsThrough(m) skips events until one matches m
mayEmit(m) consumes the next event if it matches, otherwise does nothing
emitsError(m) the next event is an error matching m
emitsDone the stream is closed
neverEmits(m) no remaining event matches m
emitsAnyOf([...]) the next events match one of the alternatives

When you use an async matcher with plain expect (as in the first and third tests), the test is kept alive until the matcher finishes, even though the test function is synchronous. That's why those tests work without async. Use expectLater when you need to do something after the check, or, as in the last test, start listening first and then push events.

For long, branching checks, StreamQueue from package:async lets you pull events one at a time with await queue.next. See Streams for more about streams themselves.

Testing printed output

The prints matcher runs a function and checks what it wrote with print:

void greet(String name) => print('Hello, $name!');

void main() {
  test('prints', () {
    expect(() => greet('Ann'), prints('Hello, Ann!\n'));
  });
}

Each print adds a trailing newline. For code that writes to stdout directly, it's simpler to make the output destination a parameter (a StringSink) and pass a StringBuffer in tests; see Dependency injection.

Skipping tests, timeouts and platforms

test() and group() take optional named parameters that change how a test runs. This file also shows printOnFailure, which records a message that's printed only if the test fails, so passing runs stay quiet:

// test/opts_test.dart
import 'dart:io';

import 'package:myapp/myapp.dart';
import 'package:test/test.dart';

void main() {
  test('not ready yet', () {
    expect(capitalize('élan'), 'Élan');
  }, skip: 'waiting for Unicode-aware capitalize');

  test('windows only', () {
    expect(Platform.pathSeparator, r'\');
  }, testOn: 'windows');

  test('slow operation', () async {
    await Future<void>.delayed(const Duration(milliseconds: 200));
  }, timeout: const Timeout(Duration(milliseconds: 50)));

  test('printOnFailure shows context only when a test fails', () {
    final input = 'a  b';
    printOnFailure('input was: "$input"');
    expect(wordCount(input), 3);
  });
}

Output on Windows (elsewhere, windows only is reported as skipped instead):

00:00 +0: loading test/opts_test.dart
00:00 +0: not ready yet
  Skip: waiting for Unicode-aware capitalize
00:00 +0 ~1: windows only
00:00 +1 ~1: slow operation
00:00 +1 ~1 -1: slow operation [E]
  TimeoutException after 0:00:00.050000: Test timed out after 0 seconds.
  dart:isolate  _RawReceivePort._handleMessage
  
00:00 +1 ~1 -1: printOnFailure shows context only when a test fails
00:00 +1 ~1 -2: printOnFailure shows context only when a test fails [E]
  Expected: <3>
    Actual: <2>
  
  package:matcher           expect
  test/opts_test.dart 22:5  main.<fn>
  
input was: "a  b"
00:00 +1 ~1 -2: Some tests failed.

Running a subset of tests

While working on one feature, you usually want to run just a few tests.

Filter by name with --plain-name (substring) or --name / -n (regular expression). The name includes the group descriptions:

dart test --plain-name remove
00:00 +0: loading test/cart_test.dart
00:00 +0: test/cart_test.dart: remove an item in the cart
00:00 +1: test/cart_test.dart: remove an unknown item throws StateError
00:00 +2: All tests passed!
dart test -n 'add .*(twice|quantity)'
00:00 +0: test/cart_test.dart: add the same item twice increases quantity
00:00 +1: test/cart_test.dart: add rejects a non-positive quantity
00:00 +2: All tests passed!

Run the test declared on a specific line (this is what IDEs use for their "run test" buttons):

dart test "test/cart_test.dart?line=21"
00:00 +0: loading test/cart_test.dart
00:00 +0: add the same item twice increases quantity
00:00 +1: All tests passed!

Other useful options:

Option Effect
-r expanded one line per test, never overwritten (good for logs)
-r failures-only print only failing tests
-r github annotations for GitHub Actions
-j 4 run up to 4 test files concurrently
--chain-stack-traces more detailed async stack traces
--coverage=coverage collect coverage data (Code coverage)

With -r failures-only, a fully passing run of all 22 tests in this article prints a single line:

+22: All tests passed!

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents