0
0
Fluttermobile~7 mins

Mock dependencies in Flutter

Choose your learning style9 modes available
Introduction

Mock dependencies help you test parts of your app without using real services. This makes testing faster and safer.

When you want to test a widget that uses a service like a database or API without calling the real service.
When you want to check how your app behaves if a service returns certain data or errors.
When you want to run tests offline without internet access.
When you want to isolate a part of your app to find bugs easily.
Syntax
Flutter
import 'package:mocktail/mocktail.dart';

class MockService extends Mock implements RealService {}

void main() {
  final mockService = MockService();
  when(() => mockService.getData()).thenReturn('mock data');
}
Use the mocktail package in Flutter to create mocks easily.
The when function sets what the mock should return when called.
Examples
This example mocks an API service to return a test user asynchronously.
Flutter
import 'package:mocktail/mocktail.dart';

class MockApi extends Mock implements ApiService {}

final mockApi = MockApi();
when(() => mockApi.fetchUser()).thenAnswer((_) async => User(name: 'Test'));
This example mocks a database to return a list of items instantly.
Flutter
import 'package:mocktail/mocktail.dart';

class MockDatabase extends Mock implements Database {}

final mockDb = MockDatabase();
when(() => mockDb.getItems()).thenReturn(['item1', 'item2']);
Sample App

This test shows how to replace a real API call with a mock that returns 'mock data'. It helps test without calling the real API.

Flutter
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';

class ApiService {
  String fetchData() => 'real data';
}

class MockApiService extends Mock implements ApiService {}

void main() {
  test('MockApiService returns mock data', () {
    final mockApi = MockApiService();
    when(() => mockApi.fetchData()).thenReturn('mock data');

    final result = mockApi.fetchData();
    expect(result, 'mock data');
  });
}
OutputSuccess
Important Notes

Always register fallback values if your mock methods use arguments.

Mocks do not run real code, so they are fast and safe for tests.

Use mocks to simulate errors and test how your app handles them.

Summary

Mocks replace real services in tests to control behavior.

Use the mocktail package to create mocks in Flutter.

Mocks help test your app faster and more reliably.