TestingMedium30 XP4 min read
How do you mock dependencies in Flutter tests? Mockito vs Mocktail
TL;DR: Mockito uses code generation (@GenerateMocks + build_runner) to create type-safe mocks. Mocktail uses Dart's noSuchMethod without code gen, making setup faster. Both use when().thenReturn() and verify() APIs.
Full Answer
| Aspect | Mockito | Mocktail |
|---|---|---|
| Setup | @GenerateMocks + build_runner | extends Mock โ no codegen |
| Type safety | Full โ generated stubs are typed | Good โ uses noSuchMethod |
| Null safety | Full (v5+) | Full |
| Maintenance | Regenerate after class changes | No regeneration needed |
๐ฏ
Use mocktail for new projects โ no build_runner step in CI and faster iteration. Use mockito if your team already has generated mocks or needs strict type verification.
Code Examples
dartMocktail mock example
Output
// Passes โ mock returns fake data, verify confirms it was called once
Common Mistakes
- โMocking things you don't own (e.g., http.Client) โ create a wrapper interface instead
- โVerifying too much implementation detail โ prefer asserting on output/state, not every call
Interview Tip
๐ก
Explain the difference between a stub (returns a value) and a verify (asserts a call happened). Overusing verify() couples tests to implementation.
#mockito#mocktail#mocking#dependency-injection