Unit Testing in Flutter
Why Test?
Tests are small programs that check your code. They find bugs early, let you change code without fear and document how things should work. Unit tests are the fastest and cheapest kind.
| Test type | Checks | Speed |
|---|---|---|
| Unit test | A function or class | Very fast |
| Widget test | One widget or screen without a device | Fast |
| Integration test | The whole app on a device | Slow |
Your First Test
Files in the test/ folder whose names end with _test.dart are tests.
dart
// lib/calculator.dart
class Calculator {
int add(int a, int b) => a + b;
double divide(int a, int b) {
if (b == 0) throw ArgumentError('Cannot divide by zero');
return a / b;
}
}
dart
// test/calculator_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/calculator.dart';
void main() {
group('Calculator', () {
late Calculator calc;
setUp(() {
calc = Calculator(); // runs before each test
});
test('adds two numbers', () {
expect(calc.add(2, 3), 5);
});
test('divides numbers', () {
expect(calc.divide(10, 4), 2.5);
});
test('throws when dividing by zero', () {
expect(() => calc.divide(1, 0), throwsArgumentError);
});
});
}
Run the Tests
bash
flutter test
flutter test test/calculator_test.dart
flutter test --coverage
Useful Matchers
| Matcher | Meaning |
|---|---|
equals(5) or just 5 | Same value |
isTrue / isFalse | Boolean |
isNull / isNotNull | Null checks |
contains('a') | Collection or string contains |
hasLength(3) | Length |
closeTo(0.3, 0.001) | Numbers close to each other |
isA<String>() | Type check |
throwsException | Code throws |
Testing a ChangeNotifier
dart
test('cart total adds prices and notifies', () {
final cart = CartModel();
var notified = 0;
cart.addListener(() => notified++);
cart.add(const Product(1, 'Shoes', 50));
cart.add(const Product(2, 'Bag', 30));
expect(cart.count, 2);
expect(cart.total, 80);
expect(notified, 2);
});
Testing Async Code
dart
test('loads todos from repository', () async {
final repo = FakeTodoRepository();
final todos = await repo.getTodos();
expect(todos, isNotEmpty);
});
test('stream emits numbers', () {
expect(Stream.fromIterable([1, 2, 3]), emitsInOrder([1, 2, 3, emitsDone]));
});
Mocking with mocktail
A mock is a fake object you control. It lets you test one class without a real network.
bash
flutter pub add dev:mocktail
dart
import 'package:mocktail/mocktail.dart';
class MockTodoRepository extends Mock implements TodoRepository {}
void main() {
test('service returns only open todos', () async {
final repo = MockTodoRepository();
when(() => repo.getTodos()).thenAnswer((_) async => [
const Todo(id: 1, title: 'A', completed: true),
const Todo(id: 2, title: 'B', completed: false),
]);
final service = TodoService(repo);
final open = await service.openTodos();
expect(open.length, 1);
verify(() => repo.getTodos()).called(1);
});
}
Arrange, Act, Assert: Write each test in three parts: prepare data, call the code, check the result. Name tests like sentences, such as
adds two numbers.
Conclusion
Unit tests are quick to write and run in seconds. Test your models, services and state classes, and use mocks to isolate them.
Quick Summary: Write tests in test/ with test, group, setUp and expect, run flutter test and mock dependencies with mocktail.

