Sub topic 1
Why test, and which kind of test to write
Prerequisites
This chapter assumes you already know the following:
- Basic Dart syntax, including
asyncandawait. - How to build a simple Flutter app with stateless and stateful widgets.
- How to use the
fluttercommand line tool. - How to add a dependency in
pubspec.yaml.
You do not need any testing experience. This chapter is a map of the territory. Later chapters cover each kind of test in detail.
Why test at all
A test is a small program that runs your code and checks that it did what you expected. A test suite is the collection of those programs. A suite gives you three things.
- Fast feedback. Running
flutter testtakes seconds. Launching the app, navigating to a screen and tapping through a flow by hand takes minutes, and you repeat that every time you change something. - Safe change. When you refactor, a failing test tells you which behavior broke. Without tests you find out from users.
- A written description of behavior. A test name such as
increment adds onerecords what the code is supposed to do, and it is checked on every run.
Tests also cost something. They must be written and maintained, and a badly designed test fails when you change harmless details. The goal is not the largest suite. The goal is a suite where each test earns its keep by catching a kind of bug at a low price.
The four kinds of Flutter tests
Flutter's tooling supports four kinds of tests. They differ in what they run, how fast they are, and what they can detect.
Unit tests
A unit test checks one function, method or class in isolation. It uses plain Dart and does not build any widgets. It runs on your development machine in the Dart VM, so it is very fast.
Use unit tests for business logic: parsing JSON, validating a form field, calculating a price, or a state holder such as a view model.
import 'package:flutter_test/flutter_test.dart';
int totalCents(List<int> prices) => prices.fold(0, (sum, p) => sum + p);
void main() {
test('totalCents adds all prices', () {
expect(totalCents([100, 250, 50]), 400);
});
test('totalCents of an empty list is zero', () {
expect(totalCents([]), 0);
});
}Widget tests
A widget test builds a widget, or a whole screen, inside a test environment. It then finds elements, simulates taps and text entry, and checks the result. Flutter calls this a component test in some places. It does not need a device or emulator. Flutter runs the widget framework headlessly, with a simulated screen, and you control time yourself.
Use widget tests to check that a screen shows the right text for a given state, that a button calls the right code, or that an error message appears after invalid input.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('shows the greeting', (tester) async {
await tester.pumpWidget(
const MaterialApp(home: Scaffold(body: Text('Hello'))),
);
expect(find.text('Hello'), findsOneWidget);
});
}Widget tests are slower than unit tests but still fast, usually milliseconds to a few hundred milliseconds each.
Golden tests
A golden test is a widget test that compares the rendered pixels of a widget with a stored image, called the golden file. If the output differs, the test fails. You regenerate the golden file on purpose, when you intend the appearance to change.
Use golden tests for visual regressions: spacing, colors, fonts, and layout at different sizes. They catch things that find.text cannot, such as a widget that exists but is clipped or the wrong color. The trade-off is brittleness. Rendering can differ between operating systems, so goldens often need to be generated and checked on the same platform, usually your CI machine.
Integration tests
An integration test launches the real app on a device, emulator or desktop window and drives it through complete flows. It uses the integration_test package and the same WidgetTester API as widget tests. It exercises real plugins, real navigation, and, if you allow it, real network and storage.
Use integration tests for a few critical journeys, such as sign-in, checkout, or first launch. They are the slowest and most fragile kind, because they depend on a device, a build, and often on external services.
Comparing the four kinds
| Kind | Runs on | Speed | Typical cost to maintain | Catches |
|---|---|---|---|---|
| Unit | Dart VM on your machine | Milliseconds | Low | Logic errors |
| Widget | Simulated Flutter environment | Tens to hundreds of milliseconds | Medium | Wrong UI for a state, broken interactions |
| Golden | Simulated Flutter environment | Similar to widget tests | Medium to high | Visual regressions |
| Integration | Real device or emulator | Seconds to minutes | High | Wiring problems, plugin and platform issues |
The testing pyramid
The testing pyramid is a guideline for how many tests of each kind to write. Many cheap tests sit at the bottom. Few expensive tests sit at the top.
The shape follows from the cost and the diagnosis value of each layer.
- A failing unit test points at one class. A failing integration test only tells you that something in the whole stack broke, and you must investigate.
- Slow tests discourage you from running the suite often. If the suite takes ten minutes, people stop running it before committing.
- Flaky tests, which pass and fail without code changes, are more common near the top. A suite you cannot trust is worse than a smaller suite you can.
A common split for an app is: most behavior covered by unit and widget tests, a small set of goldens for design-critical components, and a handful of integration tests for the journeys that must never break.
Choosing a test type for a given behavior
Ask what could go wrong and where the cheapest place to detect it is. Start from the lowest layer that can actually see the problem.
Some examples:
- A function that formats a price as
$12.50. Unit test. No widget is needed. - A login form that shows "Password too short" under the field. Widget test. It needs a widget tree, but not a device.
- A card whose shadow and corner radius must match the design. Golden test. The semantic content is the same either way, so only pixels reveal the problem.
- Taking a photo with the camera plugin and uploading it. Integration test. The simulated environment has no real camera.
- A shopping cart that totals items with discounts. Unit test the calculation thoroughly. Add one widget test that the total is displayed.
The last example shows a pattern: test the same feature at several layers, but put the detailed cases at the lowest layer. Twenty discount rules belong in unit tests. The widget test only needs to show that the screen renders whatever the logic returns.
Common mistakes
- Testing everything through the UI. Checking a calculation by tapping through a screen is slow and makes failures hard to diagnose. Move the logic into a class you can unit test.
- Writing only integration tests. They are tempting because they resemble what a user does, but a large suite of them is slow and flaky.
- Treating golden tests as a replacement for assertions. A golden says the picture did not change. It does not say that the picture is correct.
- Testing the framework. A test that checks that
Text('Hello')displays "Hello" verifies Flutter, not your code. Test your own decisions. - Asserting on implementation details. A test that fails when you rename a private variable gives no information about behavior. Assert on what a user or caller can observe.
Where this fits in the rest of the tutorial
The next chapters set up the test project and run tests, then build up from unit tests to widget tests, test doubles, goldens, integration tests, coverage and continuous integration. Each chapter keeps to the same idea from this one: use the cheapest test that can see the problem.
Exercise
You are building an order screen. List four behaviors and say which test type fits each best: (1) a function that applies a 10% discount to orders over 100, (2) a "Place order" button that is disabled while the form is invalid, (3) the order summary card must keep its exact spacing and colors from the design, (4) placing an order must work end to end with the real payment plugin on a phone.
Show answer
(1) Unit test, because it is pure logic and the many discount cases are cheap to check there. (2) Widget test, because it needs the widget tree, form input and a check on the button state, but no device. (3) Golden test, because only a pixel comparison detects spacing and color changes. (4) Integration test, because it needs the real app and a real plugin on a device or emulator.
Exercise
A teammate's suite has 5 unit tests and 80 integration tests, and it takes 25 minutes to run. Developers now skip running it locally. Which problems from this chapter does this show, and what would you change first?
Show answer
The suite is inverted: it has many slow, flaky top-layer tests and few cheap lower-layer tests. Slow runs discourage frequent use, and a failure in an integration test is hard to diagnose. Move detailed logic cases into unit tests and screen-state cases into widget tests, then keep integration tests only for a few critical journeys.