Introduction
Mock dependencies help you test parts of your app without using real services. This makes testing faster and safer.
Mock dependencies help you test parts of your app without using real services. This makes testing faster and safer.
import 'package:mocktail/mocktail.dart'; class MockService extends Mock implements RealService {} void main() { final mockService = MockService(); when(() => mockService.getData()).thenReturn('mock data'); }
mocktail package in Flutter to create mocks easily.when function sets what the mock should return when called.import 'package:mocktail/mocktail.dart'; class MockApi extends Mock implements ApiService {} final mockApi = MockApi(); when(() => mockApi.fetchUser()).thenAnswer((_) async => User(name: 'Test'));
import 'package:mocktail/mocktail.dart'; class MockDatabase extends Mock implements Database {} final mockDb = MockDatabase(); when(() => mockDb.getItems()).thenReturn(['item1', 'item2']);
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.
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'); }); }
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.
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.
print(service.getData())?
class MockService extends Mock implements Service {}
final service = MockService();
when(() => service.getData()).thenReturn('Mocked Data');
print(service.getData());class MockService extends Mock implements Service {}
final service = MockService();
when(service.getData()).thenReturn('Data');Pass the test and this pattern moves unknown