Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 61 ยท Real-World Dart

Testing with package:test

Write Dart tests with package:test: test, group, expect, matchers, setUp, async tests and fakes instead of mocks, with a runnable plain-assertion stand-in.

A test is a small program that checks that your code does what you think it does, and keeps checking every time you change something. Dart's standard tool is the test package, which you run with dart test. Flutter adds flutter_test on top of the same ideas.

This lesson shows real Dart tests (read-only here) and builds a tiny test framework in TypeScript so you can see how test, group, expect and matchers fit together. Plain assertions are enough to run the stand-ins; the Dart code is what you will write in a real project.

Setting up

Add the package as a development dependency, because your app does not need it at run time:

TEXT
dart pub add --dev test

By convention, tests live in the test/ folder and their file names end in _test.dart. dart test finds and runs them all.

Imagine this small library in lib/cart.dart:

DART
class Item {
  final String name;
  final int priceCents;
  final int quantity;

  const Item(this.name, this.priceCents, [this.quantity = 1]);
}

class Cart {
  final List<Item> _items = [];

  void add(Item item) {
    if (item.quantity <= 0) {
      throw ArgumentError.value(item.quantity, 'quantity', 'must be positive');
    }
    _items.add(item);
  }

  int get totalCents =>
      _items.fold(0, (sum, i) => sum + i.priceCents * i.quantity);

  bool get isEmpty => _items.isEmpty;
}

Your first test

A test is a call to test(description, body). The body calls expect(actual, matcher). If a check fails, the test fails with a readable message.

DART
import 'package:test/test.dart';
import 'package:shop/cart.dart';

void main() {
  test('an empty cart totals zero', () {
    final cart = Cart();
    expect(cart.totalCents, equals(0));
    expect(cart.isEmpty, isTrue);
  });

  test('the total multiplies price by quantity', () {
    final cart = Cart()
      ..add(const Item('pen', 150, 4))
      ..add(const Item('book', 1200));

    expect(cart.totalCents, 1800);
  });
}

The second expect passes a plain 1800 as the matcher. When you give a value that is not a matcher, expect wraps it in equals. Writing the descriptions as sentences ("the total multiplies price by quantity") makes the test report read like a specification.

A good test follows three steps, often called arrange, act, assert: build the objects, call the code, check the result. Keep each test to one idea so a failure points to one cause.

Matchers

A matcher describes what you expect. The library has many; these cover most needs:

Matcher Passes when
equals(x) the value is == to x (also compares lists and maps deeply)
isTrue, isFalse, isNull, isNotNull the obvious
isA<T>() the value has type T
greaterThan(n), lessThanOrEqualTo(n) numeric comparisons
closeTo(x, delta) a double is within delta of x
contains(x) a string, list or map contains x
isEmpty, hasLength(n) collections and strings
startsWith(s), matches(regExp) strings
throwsA(matcher) calling a function throws a matching error
completion(matcher) a Future completes with a matching value

For floating-point numbers, never compare with equals: 0.1 + 0.2 is not exactly 0.3. Use closeTo(0.3, 1e-9).

To check an exception, pass a function to expect, not the result of calling it:

DART
test('rejects a zero quantity', () {
  final cart = Cart();
  expect(() => cart.add(const Item('pen', 150, 0)), throwsArgumentError);
  expect(
    () => cart.add(const Item('pen', 150, -1)),
    throwsA(isA<ArgumentError>().having((e) => e.name, 'name', 'quantity')),
  );
});

If you called cart.add(...) directly, the exception would escape before expect ran. having checks a property of the thrown object. Ready-made matchers such as throwsArgumentError, throwsStateError and throwsFormatException exist for the common error types.

TypeScript A mini test framework (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Grouping and shared setup

group bundles related tests under a shared name. setUp runs before each test in the group and tearDown after it, so every test starts from a fresh state:

DART
void main() {
  group('Cart', () {
    late Cart cart;

    setUp(() {
      cart = Cart();
    });

    test('starts empty', () {
      expect(cart.isEmpty, isTrue);
    });

    group('with items', () {
      setUp(() {
        cart
          ..add(const Item('pen', 150))
          ..add(const Item('book', 1200));
      });

      test('is not empty', () => expect(cart.isEmpty, isFalse));
      test('adds up the prices', () => expect(cart.totalCents, 1350));
    });
  });
}

The late variable is assigned in setUp before any test reads it. Tests must not depend on each other or on their order: shared state between tests is the main source of flaky suites, and that is exactly what setUp prevents. setUpAll and tearDownAll run once per group, for expensive resources such as a database.

Testing async code

A test body may be async. Return or await the Future, and the runner waits for it:

DART
Future<int> loadCount() async {
  await Future<void>.delayed(const Duration(milliseconds: 10));
  return 3;
}

void main() {
  test('awaits a result', () async {
    expect(await loadCount(), 3);
  });

  test('uses completion', () {
    expect(loadCount(), completion(equals(3)));
  });

  test('a failing future', () {
    expect(Future<int>.error(StateError('boom')), throwsStateError);
  });

  test('a stream emits in order', () {
    final stream = Stream.fromIterable([1, 2, 3]);
    expect(stream, emitsInOrder([1, 2, 3, emitsDone]));
  });
}

Notice the traps: a test whose body forgets to await or return a Future can finish before the check runs and pass by accident. The completion and emitsInOrder matchers wait for you. Tests have a default 30-second timeout, so a stuck Future becomes a clear failure rather than a hanging build. See futures and streams for the underlying concepts.

Isolating code with fakes

Code that talks to a network, a clock or a disk is hard to test, because the outside world is slow and unpredictable. The cure is to depend on an interface and pass in a replacement during tests. Every Dart class is also an interface, so no special syntax is needed:

DART
abstract class UserApi {
  Future<String> fetchName(int id);
}

class Greeter {
  final UserApi api;
  Greeter(this.api);

  Future<String> greet(int id) async => 'Hello, ${await api.fetchName(id)}!';
}

class FakeUserApi implements UserApi {
  final calls = <int>[];

  @override
  Future<String> fetchName(int id) async {
    calls.add(id);
    return 'Ada';
  }
}

void main() {
  test('greets the user by name', () async {
    final api = FakeUserApi();
    expect(await Greeter(api).greet(7), 'Hello, Ada!');
    expect(api.calls, [7]);
  });
}

A hand-written fake like FakeUserApi is often the clearest choice: it is plain code, easy to read, and records what happened. When you need many variations, the mocktail and mockito packages create mocks that return preset answers and let you verify calls. Use the lightest tool that works, and test behavior (what comes out) rather than implementation (which private helper was called).

TypeScript Injecting a fake dependency (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Running and organizing tests

  • dart test runs everything; dart test test/cart_test.dart runs one file; dart test -n 'adds up' runs tests whose name matches.
  • Use skip: 'reason' on a test you must disable, and tags to split slow tests from fast ones.
  • Test the edges: empty input, one item, the largest allowed value, invalid input, and the error messages you promise.
  • A test you have never seen fail proves little. When fixing a bug, first write a test that fails, then make it pass.
  • Run dart test --coverage and a coverage tool to find untested code, but treat the number as a hint, not a goal.
flowchart LR
    A["Arrange<br/>build objects"] --> B["Act<br/>call the code"]
    B --> C["Assert<br/>expect(actual, matcher)"]
    C --> D{"Match?"}
    D -->|"yes"| P["Test passes"]
    D -->|"no"| F["Test fails<br/>with a message"]

Each test builds its own state, runs the code once and compares the result with a matcher.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do tests normally live, and how are they named?

    dart test looks in the test folder for files ending in _test.dart.
  2. 2. How do you check that a function throws an ArgumentError?

    Pass a function so expect can call it and catch the error. Calling cart.add directly would throw before expect runs.
  3. 3. Why use closeTo for doubles?

    Rounding errors mean a calculation may differ slightly from the expected literal; closeTo allows a small tolerance.
  4. 4. What does setUp do inside a group?

    setUp runs before each test; setUpAll runs only once per group.
  5. 5. What is a good reason to use a hand-written fake?

    A class implementing the same interface lets the test control the answers and record calls without a real network or disk.

Summary

  • Put tests in test/*_test.dart, import package:test/test.dart and run dart test.
  • test defines a case, group organizes cases, setUp gives each one fresh state.
  • expect(actual, matcher) compares; learn equals, isA, closeTo, contains, throwsA and completion.
  • Pass a function to expect to test exceptions; await or return futures in async tests.
  • Depend on interfaces and use fakes (or mocktail/mockito) to isolate network, clock and disk.

Next: Effective Dart: style, lints and formatting.