Testing BLoCs with bloc_test and Mocktail
Write deterministic unit tests for blocs using bloc_test expectations and mocked dependencies.
Why BLoCs Need Deterministic Tests
A BLoC is a pure state machine: it takes events in and emits a predictable sequence of states out. That makes it the most testable layer of a Flutter app.
A good bloc test answers one question: given this starting state and these events, exactly which states get emitted, in what order?
- Deterministic means the same input always produces the same output sequence.
- Sources of non-determinism to eliminate: real network calls,
DateTime.now(), random values, and timers.
We solve this with two packages: bloc_test for the test harness and mocktail for faking dependencies.
Setting Up the Test Dependencies
Add the test tooling to the dev_dependencies section of pubspec.yaml. None of these ship in your production bundle.
bloc_testprovides theblocTesthelper.mocktailcreates mocks with no code generation.testgives yougroup,setUp, andexpect.
Mocktail is preferred over Mockito here because it needs no build_runner step and works cleanly with null safety.
dev_dependencies:
bloc_test: ^9.1.7
mocktail: ^1.0.4
test: ^1.25.0All lessons in this course
- Events, States, and the Cubit-vs-Bloc Decision
- Stream Transformers and Event Debouncing in BLoC
- Persisting State with HydratedBloc
- Testing BLoCs with bloc_test and Mocktail