DartAdvanced 2 min read

Dart unit testing tutorial: verify an invoice calculation

Write deterministic tests for a real calculation and distinguish a test from a debug assertion.

On this page

A useful unit test checks a behavior you care about, not the exact implementation of a loop. Begin with a small calculation whose expected result can be computed independently. Keep external I/O out of this boundary.

Create the calculation

In a package named invoice_lab, add test as a dev dependency using dart pub add --dev test. Put this function in lib/invoice.dart:

int lineTotal(int quantity, int unitPricePaise) {
  if (quantity < 1 || unitPricePaise < 0) {
    throw ArgumentError('Invalid invoice line.');
  }
  return quantity * unitPricePaise;
}

Create test/invoice_test.dart:

import 'package:invoice_lab/invoice.dart';
import 'package:test/test.dart';

void main() {
  test('two units have the expected total', () {
    expect(lineTotal(2, 15000), 30000);
  });
  test('a zero-price sample remains a valid line', () {
    expect(lineTotal(1, 0), 0);
  });
  test('invalid quantity is rejected', () {
    expect(() => lineTotal(0, 15000), throwsArgumentError);
  });
}

Run dart test. For a synchronous exception, pass a closure to expect so the matcher observes the throw. Calling the failing function before expect prevents the matcher from owning that operation.

Choose meaningful boundaries

Test normal input, the edge of a valid range and an invalid case. The expected value should come from the business rule, not from repeating the implementation inside the test. An assert in application code can be disabled; it is not a replacement for these test checks or runtime validation.

Use descriptive names and independent fixtures. A test should not depend on another test having inserted a row or changed a global variable first. Keep time and randomness injectable when they affect the result.

Exercise

Add a maximum order quantity to the contract and test the exact maximum and the next invalid value. Change the implementation deliberately and confirm the relevant test fails for the right reason. Restore it and run the full package checks.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.