Learn/Testing & Debugging/BLoC Testing & Code Coverage

BLoC Testing & Code Coverage

Test BLoC and Cubit state management with bloc_test and measure code coverage

8 min~6 min read+40 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Generating Code Coverage
  2. 2. State Transition Coverage Model
  3. 3. This Lesson In Simple Words
  4. 4. Your level focus
  5. 5. One practical habit
  6. 6. Deep Understanding Guide
  7. 7. Why this lesson matters
  8. 8. Study flow for better retention
  9. 9. Quick Glossary
  10. 10. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

BLoC Testing & Code Coverage

BLoC and Cubit are among the most popular state management solutions in Flutter, and the bloc_test package makes testing them straightforward and declarative. With bloc_test you can verify that a BLoC or Cubit emits the correct sequence of states in response to events or method calls. The blocTest function provides a structured way to set up initial state with seed, trigger actions with act, and verify emitted states with expect. Beyond state management testing, measuring code coverage helps you identify untested parts of your codebase. Flutter has built-in support for generating coverage reports that show exactly which lines are covered by your tests and which are not. Combining thorough BLoC tests with code coverage analysis ensures your app is well tested and gives you confidence when shipping updates.

dart
1// ── BLoC Testing with bloc_test ──
2// pubspec.yaml (dev_dependencies):
3// bloc_test: ^9.1.0
4// mocktail: ^1.0.0
5
6import 'package:bloc_test/bloc_test.dart';
7import 'package:flutter_test/flutter_test.dart';
8import 'package:mocktail/mocktail.dart';
9
10// Example Cubit
11class CounterCubit extends Cubit<int> {
12 CounterCubit() : super(0);
13 void increment() => emit(state + 1);
14 void decrement() => emit(state - 1);
15 void reset() => emit(0);
16}
17
18// Example BLoC
19abstract class TodoEvent {}
20class LoadTodos extends TodoEvent {}
21class AddTodo extends TodoEvent {
22 final String title;
23 AddTodo(this.title);
24}
25
26class TodoState {
27 final List<String> todos;
28 final bool isLoading;
29 const TodoState({this.todos = const [], this.isLoading = false});
30}
31
32class TodoBloc extends Bloc<TodoEvent, TodoState> {
33 final TodoRepository repository;
34 TodoBloc(this.repository) : super(const TodoState()) {
35 on<LoadTodos>((event, emit) async {
36 emit(TodoState(isLoading: true));
37 final todos = await repository.fetchTodos();
38 emit(TodoState(todos: todos, isLoading: false));
39 });
40 on<AddTodo>((event, emit) {
41 emit(TodoState(todos: [...state.todos, event.title]));
42 });
43 }
44}
45
46// Mock
47class MockTodoRepository extends Mock implements TodoRepository {}
48
49void main() {
50 // ── Cubit Tests ──
51 group('CounterCubit', () {
52 blocTest<CounterCubit, int>(
53 'emits [1] when increment is called',
54 build: () => CounterCubit(),
55 act: (cubit) => cubit.increment(),
56 expect: () => [1],
57 );
58
59 blocTest<CounterCubit, int>(
60 'emits [1, 2, 3] when increment is called three times',
61 build: () => CounterCubit(),
62 act: (cubit) {
63 cubit.increment();
64 cubit.increment();
65 cubit.increment();
66 },
67 expect: () => [1, 2, 3],
68 );
69
70 blocTest<CounterCubit, int>(
71 'emits [5, 4] when decrement is called starting from 5',
72 build: () => CounterCubit(),
73 seed: () => 5,
74 act: (cubit) => cubit.decrement(),
75 expect: () => [4],
76 );
77 });
78
79 // ── BLoC Tests with Mocking ──
80 group('TodoBloc', () {
81 late MockTodoRepository mockRepository;
82
83 setUp(() {
84 mockRepository = MockTodoRepository();
85 });
86
87 blocTest<TodoBloc, TodoState>(
88 'emits loading then loaded when LoadTodos is added',
89 setUp: () {
90 when(() => mockRepository.fetchTodos())
91 .thenAnswer((_) async => ['Buy milk', 'Walk dog']);
92 },
93 build: () => TodoBloc(mockRepository),
94 act: (bloc) => bloc.add(LoadTodos()),
95 expect: () => [
96 const TodoState(isLoading: true),
97 const TodoState(todos: ['Buy milk', 'Walk dog'], isLoading: false),
98 ],
99 verify: (_) {
100 verify(() => mockRepository.fetchTodos()).called(1);
101 },
102 );
103
104 blocTest<TodoBloc, TodoState>(
105 'emits updated list when AddTodo is added',
106 build: () => TodoBloc(mockRepository),
107 seed: () => const TodoState(todos: ['Existing']),
108 act: (bloc) => bloc.add(AddTodo('New task')),
109 expect: () => [
110 const TodoState(todos: ['Existing', 'New task']),
111 ],
112 );
113 });
114}

Generating Code Coverage

Flutter can generate an LCOV coverage report that shows which lines of code are executed during your test suite. Run the coverage command, then convert the output into an HTML report so you can visually inspect covered and uncovered lines in a browser. Coverage reports are especially useful for identifying dead code, untested edge cases, and areas of your app that need more tests. Most teams set a minimum coverage threshold and check it in their continuous integration pipeline.

dart
1// ── Generate Coverage Report ──
2// Step 1: Run tests with coverage flag
3// flutter test --coverage
4
5// Step 2: Install lcov (macOS: brew install lcov, Linux: apt install lcov)
6// Windows: use choco install lcov or WSL
7
8// Step 3: Generate HTML report
9// genhtml coverage/lcov.info -o coverage/html
10
11// Step 4: Open the report
12// open coverage/html/index.html (macOS)
13// start coverage/html/index.html (Windows)
14
15// ── Filter coverage to your source files only ──
16// lcov --remove coverage/lcov.info \
17// 'lib/generated/*' 'lib/l10n/*' \
18// -o coverage/filtered_lcov.info
19
20// ── Check coverage in CI ──
21// You can fail the build if coverage drops below a threshold:
22// flutter test --coverage
23// COVERAGE=$(lcov --summary coverage/lcov.info | grep lines | awk '{print $2}')
24// echo "Coverage: $COVERAGE"
25
26// ── Golden Tests (Snapshot Testing) ──
27// Golden tests capture a screenshot of a widget and compare
28// it against a saved reference image.
29
30import 'package:flutter/material.dart';
31import 'package:flutter_test/flutter_test.dart';
32
33void main() {
34 testWidgets('MyButton golden test', (tester) async {
35 await tester.pumpWidget(
36 MaterialApp(
37 home: Scaffold(
38 body: ElevatedButton(
39 onPressed: () {},
40 child: const Text('Submit'),
41 ),
42 ),
43 ),
44 );
45
46 // Compare against saved golden file
47 await expectLater(
48 find.byType(ElevatedButton),
49 matchesGoldenFile('goldens/my_button.png'),
50 );
51 });
52}
53
54// Run: flutter test --update-goldens (to generate/update reference images)
55// Run: flutter test (to compare against saved goldens)

blocTest Parameters

💡 blocTest Parameters

The blocTest function has several useful parameters. Use build to create the BLoC or Cubit instance. Use seed to set initial state before the test runs. Use act to trigger events or method calls. Use expect to list the exact sequence of emitted states. Use verify to check mock interactions after the test completes. Use wait with a Duration when your BLoC has debounced events or delayed emissions.

State Transition Coverage Model

For each BLoC or Cubit, map transitions as a matrix:

  • Initial to loading.
  • Loading to success.
  • Loading to failure.
  • Success to refreshed success or empty.

This transition view helps identify missing tests where bugs often hide, especially in retry and partial-failure flows.

BLoC Coverage Checklist

  • All public events or cubit methods are covered by blocTest cases.
  • State sequences are asserted in exact order where order matters.
  • Error transitions include user-facing recovery behavior.
  • Mock verification ensures side-effect collaborators are called correctly.
  • Coverage reports are reviewed for untested critical state branches.

This Lesson In Simple Words

Test BLoC and Cubit state management with bloc test and measure code coverage. State is data that changes over time and controls what users see on the screen.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Keep state as close as possible to where it is used, then lift it only when sharing is required.

Deep Understanding Guide

Why this lesson matters

State management is the difference between predictable apps and hard-to-debug UI behavior.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Trace one user action from button tap to state update to rebuilt UI.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Calling setState high in the tree when only a small part needs refresh.
  • Keeping duplicated state in multiple widgets without a single source of truth.
  • Mutating collections directly and expecting UI updates automatically.
  • Choosing a heavy state library before understanding simple local state.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one feature with local setState, then refactor it to Provider or Riverpod.
  • Create loading, success, and error states for one async user flow.
  • Write a small state diagram for a login form and implement it.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does the seed parameter do in blocTest?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • bloc: An event-to-state pattern that separates logic from UI.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

State boundaries define module boundaries, so clear ownership prevents future regressions.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "BLoC Testing & Code Coverage" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Calling setState high in the tree when only a small part needs refresh.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does the seed parameter do in blocTest?

The seed parameter sets the initial state so you can test behavior starting from a specific state without replaying prior events.

Which command generates a code coverage report in Flutter?

The flutter test --coverage command runs all tests and generates an LCOV coverage report in the coverage directory.

What does a golden test do?

Golden tests capture a pixel-level snapshot of a widget and compare it against a previously saved reference image to detect visual regressions.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue