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.
Test BLoC and Cubit state management with bloc_test and measure code coverage
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
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 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.
1// ── BLoC Testing with bloc_test ──2// pubspec.yaml (dev_dependencies):3// bloc_test: ^9.1.04// mocktail: ^1.0.056import 'package:bloc_test/bloc_test.dart';7import 'package:flutter_test/flutter_test.dart';8import 'package:mocktail/mocktail.dart';910// Example Cubit11class CounterCubit extends Cubit<int> {12CounterCubit() : super(0);13void increment() => emit(state + 1);14void decrement() => emit(state - 1);15void reset() => emit(0);16}1718// Example BLoC19abstract class TodoEvent {}20class LoadTodos extends TodoEvent {}21class AddTodo extends TodoEvent {22final String title;23AddTodo(this.title);24}2526class TodoState {27final List<String> todos;28final bool isLoading;29const TodoState({this.todos = const [], this.isLoading = false});30}3132class TodoBloc extends Bloc<TodoEvent, TodoState> {33final TodoRepository repository;34TodoBloc(this.repository) : super(const TodoState()) {35on<LoadTodos>((event, emit) async {36emit(TodoState(isLoading: true));37final todos = await repository.fetchTodos();38emit(TodoState(todos: todos, isLoading: false));39});40on<AddTodo>((event, emit) {41emit(TodoState(todos: [...state.todos, event.title]));42});43}44}4546// Mock47class MockTodoRepository extends Mock implements TodoRepository {}4849void main() {50// ── Cubit Tests ──51group('CounterCubit', () {52blocTest<CounterCubit, int>(53'emits [1] when increment is called',54build: () => CounterCubit(),55act: (cubit) => cubit.increment(),56expect: () => [1],57);5859blocTest<CounterCubit, int>(60'emits [1, 2, 3] when increment is called three times',61build: () => CounterCubit(),62act: (cubit) {63cubit.increment();64cubit.increment();65cubit.increment();66},67expect: () => [1, 2, 3],68);6970blocTest<CounterCubit, int>(71'emits [5, 4] when decrement is called starting from 5',72build: () => CounterCubit(),73seed: () => 5,74act: (cubit) => cubit.decrement(),75expect: () => [4],76);77});7879// ── BLoC Tests with Mocking ──80group('TodoBloc', () {81late MockTodoRepository mockRepository;8283setUp(() {84mockRepository = MockTodoRepository();85});8687blocTest<TodoBloc, TodoState>(88'emits loading then loaded when LoadTodos is added',89setUp: () {90when(() => mockRepository.fetchTodos())91.thenAnswer((_) async => ['Buy milk', 'Walk dog']);92},93build: () => TodoBloc(mockRepository),94act: (bloc) => bloc.add(LoadTodos()),95expect: () => [96const TodoState(isLoading: true),97const TodoState(todos: ['Buy milk', 'Walk dog'], isLoading: false),98],99verify: (_) {100verify(() => mockRepository.fetchTodos()).called(1);101},102);103104blocTest<TodoBloc, TodoState>(105'emits updated list when AddTodo is added',106build: () => TodoBloc(mockRepository),107seed: () => const TodoState(todos: ['Existing']),108act: (bloc) => bloc.add(AddTodo('New task')),109expect: () => [110const TodoState(todos: ['Existing', 'New task']),111],112);113});114}
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.
1// ── Generate Coverage Report ──2// Step 1: Run tests with coverage flag3// flutter test --coverage45// Step 2: Install lcov (macOS: brew install lcov, Linux: apt install lcov)6// Windows: use choco install lcov or WSL78// Step 3: Generate HTML report9// genhtml coverage/lcov.info -o coverage/html1011// Step 4: Open the report12// open coverage/html/index.html (macOS)13// start coverage/html/index.html (Windows)1415// ── Filter coverage to your source files only ──16// lcov --remove coverage/lcov.info \17// 'lib/generated/*' 'lib/l10n/*' \18// -o coverage/filtered_lcov.info1920// ── Check coverage in CI ──21// You can fail the build if coverage drops below a threshold:22// flutter test --coverage23// COVERAGE=$(lcov --summary coverage/lcov.info | grep lines | awk '{print $2}')24// echo "Coverage: $COVERAGE"2526// ── Golden Tests (Snapshot Testing) ──27// Golden tests capture a screenshot of a widget and compare28// it against a saved reference image.2930import 'package:flutter/material.dart';31import 'package:flutter_test/flutter_test.dart';3233void main() {34testWidgets('MyButton golden test', (tester) async {35await tester.pumpWidget(36MaterialApp(37home: Scaffold(38body: ElevatedButton(39onPressed: () {},40child: const Text('Submit'),41),42),43),44);4546// Compare against saved golden file47await expectLater(48find.byType(ElevatedButton),49matchesGoldenFile('goldens/my_button.png'),50);51});52}5354// Run: flutter test --update-goldens (to generate/update reference images)55// Run: flutter test (to compare against saved goldens)
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.
For each BLoC or Cubit, map transitions as a matrix:
This transition view helps identify missing tests where bugs often hide, especially in retry and partial-failure flows.
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.
Think in architecture, reliability, and team-level maintainability.
Keep state as close as possible to where it is used, then lift it only when sharing is required.
State management is the difference between predictable apps and hard-to-debug UI behavior.
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.
The seed parameter sets the initial state so you can test behavior starting from a specific state without replaying prior events.
The flutter test --coverage command runs all tests and generates an LCOV coverage report in the coverage directory.
Golden tests capture a pixel-level snapshot of a widget and compare it against a previously saved reference image to detect visual regressions.
Something seems incorrect, unclear, or missing? Let us know.
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