Back to results for “UI Testing”
Flutter › Unit Testing in Flutter

How do you properly use the mockito package to create a genuine mock object specifically for testing a class that genuinely depends on an external dependency, such as a network client or a database repository?

Intermediate

Answer

The mockito package lets you generate a genuine mock implementation of a given interface or class, letting you precisely configure exactly what that particular mock should genuinely return when a given specific method is actually called, and then subsequently verify exactly how many times, and with exactly what specific arguments, that particular mocked method was genuinely actually called, letting you thoroughly test a class's own genuine business logic in complete isolation without needing an actual real implementation of whatever external dependency it genuinely relies on.
class MockApiClient extends Mock implements ApiClient {}

test('fetchUser returns parsed user', () async {
  final mockClient = MockApiClient();
  when(mockClient.get('/user')).thenAnswer((_) async => {'name': 'Alex'});
  final service = UserService(mockClient);
  expect((await service.fetchUser()).name, 'Alex');
});
Real-world example A test for a UserService class uses a mockito generated MockApiClient configured to return predetermined test data, thoroughly verifying the UserService's own actual parsing logic without ever needing to genuinely make a real network request.

Common follow-ups: What genuinely does the verify function specifically let you actually properly assert about a given mocked method call?;What is the specific practical difference between mockito's own traditional mocks and the considerably newer code generation based Mockito annotations?