Bidev
IntermediateTesting

How do you mock dependencies in Flutter tests?

Short Answer

Use the mocktail package (or mockito) to create a fake implementation of a class/interface, stub its methods with when().thenAnswer(), and inject the mock wherever the real dependency would normally be provided.

For a class under test that depends on a repository or API client, you don't want your unit test making real network calls. mocktail lets you write class MockUserRepository extends Mock implements UserRepository {}, then stub specific method calls with when(() => mock.getUser(any())).thenAnswer((_) async => testUser).

The class under test then receives the mock via constructor injection — exactly why dependency injection matters for testability — and you can assert on how it was called with verify(() => mock.getUser('123')).called(1).

Code Example

class MockUserRepository extends Mock implements UserRepository {}

void main() {
  late MockUserRepository mockRepo;

  setUp(() {
    mockRepo = MockUserRepository();
  });

  test('returns user from repository', () async {
    when(() => mockRepo.getUser('1')).thenAnswer((_) async => User(id: '1', name: 'Ana'));

    final result = await mockRepo.getUser('1');

    expect(result.name, 'Ana');
    verify(() => mockRepo.getUser('1')).called(1);
  });
}

Common Mistakes

  • ×Testing a class that constructs its own dependencies internally instead of receiving them via constructor injection — this makes mocking impossible without refactoring.
  • ×Forgetting to register a fallback value for custom argument types when using any() with mocktail, which throws at runtime.