Sub topic 11
Testing Cubits and Blocs with bloc_test
This chapter assumes you can write a Cubit and a Bloc, you know the TodosState model and TodosRepository from earlier chapters, and you have written a basic flutter_test test. You will learn to assert the exact sequence of states a Cubit or Bloc emits, to stub a repository with mocktail, and to avoid the usual timing and equality mistakes.
Why Cubits and Blocs are easy to test
A Cubit or Bloc is a plain Dart object. It takes inputs (method calls or events) and produces outputs (a sequence of states). It needs no widgets, no BuildContext and no running app. Because its dependencies arrive through the constructor, a test can replace the repository with a fake.
This makes the test shape the same for every Cubit and Bloc:
- Create the object with fake dependencies.
- Trigger a method call or add an event.
- Compare the emitted states with the states you expect.
Setup
Add the test packages as dev dependencies.
dev_dependencies:
flutter_test:
sdk: flutter
bloc_test: ^9.1.0
mocktail: ^1.0.0bloc_test provides blocTest, MockCubit and MockBloc. mocktail creates mocks without code generation. Check pub.dev for the current versions.
Your first blocTest
blocTest wraps a normal test call. It builds the Cubit, runs your action, waits for the states to settle, and compares them with expect.
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:todos_app/counter/counter.dart';
void main() {
group('CounterCubit', () {
test('initial state is 0', () {
expect(CounterCubit().state, 0);
});
blocTest<CounterCubit, int>(
'emits [1] when increment is called',
build: CounterCubit.new,
act: (cubit) => cubit.increment(),
expect: () => [1],
);
blocTest<CounterCubit, int>(
'emits [4] when decrement is called from seed 5',
build: CounterCubit.new,
seed: () => 5,
act: (cubit) => cubit.decrement(),
expect: () => [4],
);
});
}The import path uses todos_app as a placeholder. Replace it with your package name and file.
The initial state is not part of the expect list. blocTest only records states emitted after build. To check the initial state, use a plain test as in the first case.
The parameters of blocTest
| Parameter | Purpose |
|---|---|
| `setUp` | Runs before `build`. Use it to stub mocks. |
| `build` | Returns a fresh Cubit or Bloc. Required. |
| `seed` | Sets the starting state without emitting it. |
| `act` | Calls methods or adds events. |
| `wait` | Waits a `Duration` after `act`. Use it for debounce or delays. |
| `skip` | Ignores the first N emitted states. |
| `expect` | Returns the expected list of states or matchers. |
| `verify` | Runs extra checks, such as mock call counts. |
| `errors` | Returns the expected list of uncaught errors. |
| `tearDown` | Runs cleanup after the test. |
Testing an async Cubit with a mocked repository
Create a mock by extending Mock and implementing the repository interface. Stub methods with when, and check calls with verify.
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:todos_app/todos/todos.dart';
class MockTodosRepository extends Mock implements TodosRepository {}
void main() {
late TodosRepository repository;
setUp(() {
repository = MockTodosRepository();
});
group('TodosCubit', () {
test('initial state is TodosState()', () {
expect(TodosCubit(repository).state, const TodosState());
});
blocTest<TodosCubit, TodosState>(
'emits [loading, success] when fetchTodos succeeds',
setUp: () {
when(() => repository.fetchTodos())
.thenAnswer((_) async => ['Write tests', 'Ship feature']);
},
build: () => TodosCubit(repository),
act: (cubit) => cubit.load(),
expect: () => const [
TodosState(status: TodosStatus.loading),
TodosState(
status: TodosStatus.success,
todos: ['Write tests', 'Ship feature'],
),
],
verify: (_) {
verify(() => repository.fetchTodos()).called(1);
},
);
blocTest<TodosCubit, TodosState>(
'emits [loading, failure] when fetchTodos throws',
setUp: () {
when(() => repository.fetchTodos()).thenThrow(Exception('boom'));
},
build: () => TodosCubit(repository),
act: (cubit) => cubit.load(),
expect: () => const [
TodosState(status: TodosStatus.loading),
TodosState(
status: TodosStatus.failure,
errorMessage: 'Exception: boom',
),
],
);
});
}blocTest awaits the Future returned by act, so await-ing inside load() finishes before the comparison. The comparison relies on Equatable. Each expected TodosState is compared by its props, not by identity.
The failure test uses thenThrow. Since fetchTodos returns a Future, thenThrow makes the call throw synchronously. Inside load() that still lands in the try block, so the test passes. To model an asynchronous failure, use thenAnswer((_) async => throw Exception('boom')).
Testing a Bloc
A Bloc test looks the same, except act adds events.
blocTest<CounterBloc, int>(
'emits [1, 2] when CounterIncremented is added twice',
build: CounterBloc.new,
act: (bloc) => bloc
..add(CounterIncremented())
..add(CounterIncremented()),
expect: () => [1, 2],
);Events are handled in the order they arrive, unless you configured a transformer. You can test a transformer by controlling timing. The SearchBloc from the concurrency chapter uses restartable(). This test passes a fake search function where the first query is slower than the second:
blocTest<SearchBloc, List<String>>(
'keeps only the result of the newest query',
build: () => SearchBloc((query) async {
await Future<void>.delayed(
Duration(milliseconds: query == 'a' ? 100 : 10),
);
return [query];
}),
act: (bloc) => bloc
..add(SearchQueryChanged('a'))
..add(SearchQueryChanged('b')),
wait: const Duration(milliseconds: 200),
expect: () => [
['b'],
],
);Without restartable(), the state would end with the result for a, or contain both results. The wait value must be longer than the slowest fake delay.
Choosing what to assert
- Use
expectfor the state sequence. It is the main contract of your Cubit. - Use
verifyfor side effects on dependencies, such as "the repository was called once". - Use
skipwhen you only care about the final state of a long sequence, for exampleskip: 1to ignoreloading. - Use
errorswhen a Bloc or Cubit is supposed to report an uncaught error. Without it, an unexpected error fails the test.
blocTest<TodosCubit, TodosState>(
'ends in success',
setUp: () {
when(() => repository.fetchTodos()).thenAnswer((_) async => ['One']);
},
build: () => TodosCubit(repository),
act: (cubit) => cubit.load(),
skip: 1,
expect: () => const [
TodosState(status: TodosStatus.success, todos: ['One']),
],
);Common errors
- The test fails although the states look identical. The state class probably lacks
Equatableor has an incompletepropslist. Two instances then compare by identity. Include every field inprops. expectis missing a state you emit. A Cubit does not emit a state equal to the current one. Ifemitreceives a value that equalsstate, nothing is emitted, and the test expects one state too many. This is the correct behavior of the library.- A
nulltype error from a mock. An unstubbedmocktailmethod returnsnull, which fails for non-nullable return types. Stub every method the code under test calls. any()fails for a custom type.mocktailneedsregisterFallbackValue(YourType())once, usually insetUpAll, before you useany()with that type.- The expected state never arrives. Debounce, throttle or delayed work finishes after
actreturns. Addwaitwith a longer duration. - Tests affect each other. Do not share a Cubit instance between tests. Create it inside
buildso each test gets a fresh one thatblocTestcloses for you.
Testing widgets with a mocked Cubit
Widget tests should not run real logic. bloc_test offers MockCubit for this. You stub state and stream, then pump the widget inside a BlocProvider.value.
class MockCounterCubit extends MockCubit<int> implements CounterCubit {}
void main() {
testWidgets('shows the current count', (tester) async {
final cubit = MockCounterCubit();
when(() => cubit.state).thenReturn(42);
await tester.pumpWidget(
MaterialApp(
home: BlocProvider<CounterCubit>.value(
value: cubit,
child: const CounterView(),
),
),
);
expect(find.text('42'), findsOneWidget);
});
}Use .value because the test owns the mock, and BlocProvider would otherwise try to close it.
Exercise
Write a blocTest for TodosCubit where the repository returns an empty list. What states do you expect, and which blocTest parameter would you add to check that the repository was called exactly once?
Show answer
The expected states are const [TodosState(status: TodosStatus.loading), TodosState(status: TodosStatus.success, todos: [])]. The loading state differs from the initial state because status changes, so it is emitted. In setUp, stub fetchTodos with thenAnswer((_) async => <String>[]). Add verify: (_) { verify(() => repository.fetchTodos()).called(1); } to check the call count.
Exercise
A test expects [1, 1] after calling increment twice on a CounterCubit that starts at 0, but the test fails. What is the real emitted sequence, and why?
Show answer
The real sequence is [1, 2]. Each increment emits state + 1, and the state is 1 after the first call, so the second call emits 2. Fix the expectation to [1, 2]. If you actually want two identical emissions to appear, that is impossible, because Bloc and Cubit skip a state equal to the current one.