NetworkingMedium30 XP3 min read
How do you mock API calls in Flutter tests?
TL;DR: For Dio: use DioMixin + MockAdapter or inject a mock repository with mocktail. For http package: inject a mock http.Client. For repositories: implement the interface with a FakeRepository (in-memory data) instead of using mock frameworks.
Full Answer
- ▸FakeRepository: Implement the interface with an in-memory list — most reliable, no mock framework needed
- ▸Mocktail: when(() => repo.getX()).thenAnswer((_) async => fakeData) — for mocking specific calls
- ▸DioHttpClientAdapter: Replace Dio's transport layer for low-level HTTP testing
- ▸http.MockClient: For apps using the http package — inject a mock that returns predefined responses
🎯
Prefer FakeRepository over mock objects. Mocks verify interactions (was it called?). Fakes verify behavior (does it return the right data?). Fakes are more realistic and less brittle.
Code Examples
dartFakeRepository vs Mocktail
Output
// FakeRepository: realistic in-memory implementation // Mocktail: precise control over return values and exceptions
Common Mistakes
- ✗Mocking at the Dio level for unit tests — you're testing Dio, not your app logic
- ✗Using real HTTP calls in unit tests — flaky, slow, requires network
Interview Tip
💡
Know when to use fakes vs mocks: fakes for happy-path behavior testing, mocks for verifying interactions (that a method was called with specific arguments) or forcing error paths.
#mock#testing#http-mock#mocktail#dio-mock