TExcelTAD
Home › Dart › Testing with package:test

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:test needs 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-made expect so you can experiment in the browser.

Setup

dart create already adds test to dev_dependencies. Otherwise:

bash · try it yourself
dart pub add --dev test
Resolving 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:

dart
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:

dart
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);
    });
  });
}
bash · try it yourself
dart test
00:00 +3: All tests passed!

When something breaks, the runner tells you exactly what was expected and what it got:

bash · try it yourself
dart test
00: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:

dart · try it yourself
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'^-|-
  

), '');

void main() {
  expectEq(slugify('Hello World'), 'hello-world', 'spaces become dashes');
  expectEq(slugify('  Dart 3 is here! '), 'dart-3-is-here', 'trims and strips punctuation');
  expectEq(slugify('Phở Bò'), 'ph-b', 'non-ASCII letters are dropped');
  expectEq(slugify('C++ & C#'), 'c-and-c', 'symbols (intentionally failing)');
  print('\n$passed passed, $failed failed');
}
PASS  spaces become dashes
PASS  trims and strips punctuation
PASS  non-ASCII letters are dropped
FAIL  symbols (intentionally failing)
      expected: c-and-c
      actual:   c-c

3 passed, 1 failed

The failing test reveals a real design question: should & become and? Tests make such decisions explicit.

Testing async code

Test bodies can be async; the runner waits for the returned future. Matchers like completion and emitsInOrder work on futures and streams:

dart
test('fetches a user', () async {
  final repo = FakeUserRepository();
  final user = await repo.find(1);
  expect(user.name, 'Lan');
});

test('countdown stream', () {
  expect(countdown(3), emitsInOrder([3, 2, 1, emitsDone]));
});

Testable design: inject dependencies

Code that calls DateTime.now() or the network directly is hard to test. Pass those in instead, so tests can provide fakes:

dart · try it yourself
typedef Clock = DateTime Function();

class Greeter {
  final Clock now;
  Greeter({Clock? clock}) : now = clock ?? DateTime.now;

  String greet(String name) {
    final h = now().hour;
    final part = h < 12 ? 'morning' : (h < 18 ? 'afternoon' : 'evening');
    return 'Good $part, $name';
  }
}

void main() {
  // In a test, freeze time:
  final morning = Greeter(clock: () => DateTime(2025, 1, 1, 8));
  final night = Greeter(clock: () => DateTime(2025, 1, 1, 22));
  print(morning.greet('Bao'));
  print(night.greet('Bao'));
}
Good morning, Bao
Good evening, Bao

For larger fakes, the mocktail package generates mock objects with when(...)/verify(...) APIs.

Useful dart test options

Command Effect
dart test Run everything under test/
dart test test/cart_test.dart One file
dart test --name "sums" Tests whose name matches
dart test --coverage=coverage Collect coverage data
dart test -p chrome Run in a browser

Tip: Write the test for a bug before fixing it. Watch it fail, fix the code, watch it pass — and that bug can never silently return.

Test yourself

Where do package:test test files go, and how are they named?

  1. lib/, *.test.dart
  2. test/, *_test.dart
  3. bin/, test_*.dart
  4. Anywhere, *.spec.dart

Which matcher checks that a function throws a FormatException?

  1. throwsA(isA<FormatException>())
  2. equals(FormatException)
  3. isA<FormatException>()
  4. throws(FormatException)

What does setUp do inside a group?

  1. Runs once before the whole file
  2. Runs before each test in the group
  3. Runs after each test
  4. Installs dependencies