Unit test of repository with Mocktail in Flutter: solved exercise
Unit test of repository with Mocktail in Flutter: solved exercise
Testing only the UI is not enough. Business logic in repositories and use cases needs its own unit tests, isolated from the network and Flutter. mocktail lets you create mocks without code generation, which simplifies setup considerably.
Problem statement
Design a PostRepository contract, a GetPostsUseCase that filters empty posts, and write unit tests that verify correct behavior on success and error by mocking the repository.
Dependencies
Solution: domain classes
Solution: tests with Mocktail
How to run the tests
Expected result
Three cases pass: filtered and sorted list, propagated exception, empty list.
Common mistakes
- Unconfigured mock: forgetting
when(...)before calling a mocked method throwsMissingStubError. Configure stubs insetUpor at the start of each test. - Equality not implemented in the model: if
Postdoes not override==,expect(result, [Post(...)])always fails even when values match. - Verifying without having set up the mock:
verifyworks on mocktail mocks, not real instances.
Why unit tests for domain classes are worth it
- They run in milliseconds, with no emulator or network needed.
- They document the expected behavior of business logic.
- They catch regressions when you change the use case or repository.
- They serve as executable specifications for the team.
Practical use
Any use case in a clean architecture app benefits from this type of test: list filtering, data transformation, business rules (discounts, validations, permissions).
Recommended next exercise
- Mock API in Flutter tests: solved exercise
- Flutter login integration test: solved exercise
- Repository and use cases in Flutter: solved exercise
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
FAQ
Why Mocktail instead of Mockito?
Mocktail requires no code generation with build_runner. You write the mock in one line and tests run without any pre-build step.
When to use thenAnswer vs thenReturn?
Use thenReturn for synchronous values. Use thenAnswer when the stub returns a Future or Stream.
Where do repository tests live in the project?
In test/domain/ if you follow clean architecture. The convention is to mirror the lib/ structure inside test/.