D
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

AspectMockitoMocktail
Setup@GenerateMocks + build_runnerextends Mock โ€” no codegen
Type safetyFull โ€” generated stubs are typedGood โ€” uses noSuchMethod
Null safetyFull (v5+)Full
MaintenanceRegenerate after class changesNo 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