Many Flutter projects have either no tests or hundreds of brittle ones that break on every refactor. The goal of a test suite is confidence per minute of maintenance. Here is the strategy I use, with the tools that make it cheap.
The testing pyramid for mobile
| Level | Speed | What it checks | How many |
|---|---|---|---|
| Unit | Milliseconds | Logic: use cases, mappers, BLoCs | Most |
| Widget | Fast | One screen or widget with fake dependencies | Some |
| Integration | Slow | Real app on a device or emulator, key journeys | Few |
Write many fast tests of logic, some of UI behavior, and a handful of end-to-end checks for critical flows (login, checkout).
What makes code testable
Tests are easy when dependencies are injected and the logic is separated from widgets. That is the payoff of Clean Architecture and dependency injection: a BLoC that receives a repository interface can be tested with a fake in a few lines. If a test is painful to write, treat it as feedback about the design.
Unit tests: mappers and use cases
test('OrderDto maps to Order entity', () {
final dto = OrderDto(id: '1', totalAmount: 49.9, status: 'paid');
final order = dto.toEntity();
expect(order.id, '1');
expect(order.status, OrderStatus.paid);
});
Pure functions are the highest-value tests: no mocks, no setup, no flakiness.
Testing a BLoC with bloc_test and mocktail
class MockOrderRepository extends Mock implements OrderRepository {}
void main() {
late MockOrderRepository repo;
setUp(() => repo = MockOrderRepository());
blocTest<OrdersBloc, OrdersState>(
'emits [loading, loaded] when orders load',
setUp: () => when(() => repo.getOrders())
.thenAnswer((_) async => Ok([testOrder])),
build: () => OrdersBloc(GetOrders(repo)),
act: (bloc) => bloc.add(OrdersRequested()),
expect: () => [isA<OrdersLoading>(), isA<OrdersLoaded>()],
);
blocTest<OrdersBloc, OrdersState>(
'emits [loading, failed] when the repository returns an error',
setUp: () => when(() => repo.getOrders())
.thenAnswer((_) async => const Err(OfflineFailure())),
build: () => OrdersBloc(GetOrders(repo)),
act: (bloc) => bloc.add(OrdersRequested()),
expect: () => [isA<OrdersLoading>(), isA<OrdersFailed>()],
);
}
Test the error path as carefully as the happy path; it is where production bugs hide. The same idea applies to Riverpod (override providers in a ProviderContainer) and Cubits; see choosing a state management approach.
Widget tests: behavior, not pixels
testWidgets('shows an error message and a retry button on failure', (tester) async {
final bloc = MockOrdersBloc();
whenListen(bloc, Stream<OrdersState>.empty(),
initialState: const OrdersFailed('No internet connection.'));
await tester.pumpWidget(
MaterialApp(
home: BlocProvider<OrdersBloc>.value(value: bloc, child: const OrdersView()),
),
);
expect(find.text('No internet connection.'), findsOneWidget);
expect(find.widgetWithText(ElevatedButton, 'Retry'), findsOneWidget);
});
Find widgets by what users see (text, semantics, keys) rather than by widget type or tree position, so refactors do not break tests. Remember await tester.pump() after interactions, or pumpAndSettle() when animations should finish.
Integration tests: only the journeys that cost money
Use the integration_test package on an emulator for flows like sign-in, adding to cart and paying. They are slow and can be flaky, so keep them few and stable: seed predictable data, avoid fixed delays, and wait for widgets to appear instead.
Golden tests
Golden (screenshot) tests catch visual regressions for design-system components. They are sensitive to fonts and platforms, so generate and compare them on the same CI image, and use them sparingly.
Run them in CI
# GitHub Actions step
- run: flutter test --coverage
Make the suite fast enough that nobody skips it. Chasing a coverage percentage is a trap; cover risky logic (parsing, auth, money, sync) first. Rules like the token-refresh race from JWT refresh in Flutter are exactly what a targeted test should pin down.
Common mistakes
- Mocking everything, including simple value objects.
- Asserting on internal calls instead of outcomes.
- Tests that depend on the real network, the clock or randomness.
- Skipping the failure path.
Key takeaways
- Many fast unit tests, some widget tests, few integration tests.
- Injectable dependencies make testing cheap; painful tests signal design problems.
- Test error states as seriously as success states.
- Target risky logic, not a coverage number.
Want a mobile engineer who ships tested code? Get in touch or browse my projects.