Sub topic 3
Writing your first unit tests
A unit test runs one small piece of code, such as a function or a class method, and checks its result. It doesn't start the Flutter engine, draw widgets, or touch a device. This chapter assumes you can run flutter test in a project, as covered in the setup chapter. It also assumes you know basic Dart, including classes, closures and exceptions. By the end you will be able to write tests for plain Dart logic, read failure output, and choose matchers that give clear messages.
What a unit test looks like
The flutter_test package re-exports the Dart test API: test, expect, and the matchers. A test has three parts.
- A description string that names the behavior being checked.
- A body, which is a closure that runs the code under test.
- One or more
expectcalls that compare an actual value with an expected value or a matcher.
A test passes if its body finishes without throwing. expect throws a TestFailure when the check fails, which is how a failure is reported. Any other uncaught exception also fails the test, but it is reported as an error instead of a failed expectation.
Structuring each test as arrange, act, assert keeps tests short and makes failures easy to locate.
The code under test
Put the logic in lib/, and the tests in test/. This example is a small shopping cart with no Flutter imports, which makes it a good fit for a unit test. Create lib/cart.dart in a project named my_app.
class CartItem {
const CartItem(this.name, this.priceCents, [this.quantity = 1]);
final String name;
final int priceCents;
final int quantity;
}
class Cart {
final List<CartItem> _items = [];
List<CartItem> get items => List.unmodifiable(_items);
int get totalCents =>
_items.fold(0, (sum, item) => sum + item.priceCents * item.quantity);
void add(CartItem item) {
if (item.quantity <= 0) {
throw ArgumentError.value(item.quantity, 'quantity', 'must be positive');
}
_items.add(item);
}
int totalWithDiscount(int percent) {
if (percent < 0 || percent > 100) {
throw RangeError.range(percent, 0, 100, 'percent');
}
return totalCents - totalCents * percent ~/ 100;
}
}The cart stores money as integer cents. This is a deliberate choice, because it avoids the floating-point rounding errors that make tests flaky.
Your first test file
Create test/cart_test.dart. The file name must end in _test.dart, or flutter test will not find it.
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/cart.dart';
void main() {
test('an empty cart totals zero', () {
final cart = Cart();
expect(cart.totalCents, 0);
});
test('total multiplies price by quantity', () {
final cart = Cart();
cart.add(const CartItem('Pen', 150, 3));
cart.add(const CartItem('Notebook', 400));
expect(cart.totalCents, 850);
});
test('add rejects a quantity of zero', () {
final cart = Cart();
expect(
() => cart.add(const CartItem('Pen', 150, 0)),
throwsArgumentError,
);
});
test('items cannot be modified from outside', () {
final cart = Cart();
expect(
() => cart.items.add(const CartItem('Pen', 150)),
throwsUnsupportedError,
);
});
test('discount removes a percentage of the total', () {
final cart = Cart();
cart.add(const CartItem('Notebook', 400));
expect(cart.totalWithDiscount(25), 300);
});
test('discount outside 0 to 100 throws a RangeError', () {
final cart = Cart();
expect(() => cart.totalWithDiscount(101), throwsRangeError);
});
}Run it with the commands below. Each test needs its own Cart, so the repeated final cart = Cart(); lines are intentional. The next chapter shows how group and setUp remove that repetition.
flutter test test/cart_test.dart
flutter test test/cart_test.dart --plain-name "discount"The --plain-name option runs only tests whose full name contains the given text. Use --name if you want the filter to be a regular expression.
How expect works
The signature is expect(actual, matcher). The first argument is the value your code produced. The second is either a plain value or a matcher.
When you pass a plain value, Dart wraps it in equals. For collections, equals compares deeply, so expect([1, 2], [1, 2]) passes even though the two lists are different objects. For your own classes, equals uses ==. If CartItem does not override == and hashCode, two separately created items with the same fields are not equal. Identical const instances are the exception, because Dart reuses them. This is a common cause of tests that pass with const and fail without it.
Reading a failure
If you change the expected discount result to 200, the test fails like this:
Expected: <200>
Actual: <300>The output also shows the file and line of the failing expect. A matcher that describes intent produces a better message than a manual comparison. For example, expect(items.length == 2, isTrue) only tells you that false was not true, while expect(items, hasLength(2)) reports the actual length and contents.
Common matchers
Matchers are small objects that describe a condition. You can combine them with allOf, anyOf and isNot.
| Matcher | Passes when | Example |
|---|---|---|
| `equals(x)` or a plain value | The values are equal, deeply for collections | `expect(cart.totalCents, 850)` |
| `isTrue`, `isFalse` | The value is exactly `true` or `false` | `expect(isValid, isTrue)` |
| `isNull`, `isNotNull` | The value is or is not `null` | `expect(user, isNull)` |
| `isEmpty`, `hasLength(n)` | A collection or string has no elements, or n elements | `expect(cart.items, hasLength(2))` |
| `contains(x)` | A collection or string contains x | `expect(names, contains('Pen'))` |
| `closeTo(x, delta)` | A number is within delta of x | `expect(0.1 + 0.2, closeTo(0.3, 1e-9))` |
| `greaterThan(x)` | A number is above x | `expect(total, greaterThan(0))` |
| `isA<T>()` | The value has type T | `expect(error, isA<StateError>())` |
| `throwsA(matcher)` | A function throws something matching the matcher | `expect(() => f(), throwsA(isA<StateError>()))` |
isA<T>() can be narrowed with .having, which checks a property of the value. This is useful when you care about the exception message and not only its type.
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/cart.dart';
void main() {
test('the error names the invalid field', () {
final cart = Cart();
expect(
() => cart.add(const CartItem('Pen', 150, -1)),
throwsA(
isA<ArgumentError>().having((e) => e.name, 'name', 'quantity'),
),
);
});
}Testing exceptions correctly
To test that code throws, pass a closure to expect together with a throwsA matcher or one of the shortcuts such as throwsArgumentError, throwsRangeError and throwsStateError. The closure is needed because expect must run the code itself and catch the exception.
A common mistake is to write expect(cart.totalWithDiscount(101), throwsRangeError). Here the call runs before expect is entered, so the exception escapes and the test fails with an error instead of passing. Always wrap the call in () => ....
Writing tests that stay useful
- Name each test after the behavior, not the method. "discount removes a percentage of the total" says more than "totalWithDiscount works".
- Check one behavior per test. Several
expectcalls are fine when they all describe the same behavior. - Do not share mutable objects between tests through top-level variables. Dart runs tests in a file in order, but a test that depends on state left by an earlier one breaks when you run it alone with
--plain-name. - Test the edges, not only the middle. For the discount method, that means 0, 100, a negative number, and a total that does not divide evenly.
- Avoid floating-point equality. Use integers where you can, and
closeTowhere you cannot. - Do not assert on code you did not write. A test that checks
List.unmodifiablereally is unmodifiable would test the Dart SDK. Theitemstest above is acceptable only because it protects the cart's promise to its callers.
What a plain unit test cannot do
A unit test of this kind works for pure logic. It cannot check how a widget looks or how it reacts to a tap. Those cases need widget tests, which come later. Classes that call a network or database directly are also hard to test this way, because the test would hit the real service. The dependency injection and mocking chapters cover that problem.
Exercise
Add a method bool get isEmpty to Cart that returns true when no items have been added. Then write two tests for it in test/cart_test.dart: one that checks a new cart is empty, and one that checks it is not empty after adding an item. Which matchers would you use, and why is expect(cart.isEmpty, isTrue) better than expect(cart.isEmpty == true, true)?
Show answer
Add bool get isEmpty => _items.isEmpty; to Cart. The first test creates a Cart and runs expect(cart.isEmpty, isTrue). The second adds const CartItem('Pen', 150) and runs expect(cart.isEmpty, isFalse). The isTrue matcher produces a failure message that says what was expected and what the actual value was, while the manual comparison would only report that false did not equal true, which hides which expression failed.
Exercise
A teammate writes expect(cart.totalWithDiscount(150), throwsRangeError); and the test fails with a RangeError instead of passing. What is wrong, and how do you fix it?
Show answer
The call runs before expect starts, so the exception is thrown in the test body and fails the test. Wrap the call in a closure so expect can run it and catch the exception: expect(() => cart.totalWithDiscount(150), throwsRangeError);.