Learn/Testing & Debugging/Integration Testing & Mocking

Integration Testing & Mocking

Test app flows end-to-end and mock dependencies

7 min~5 min read+40 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Choosing What To Mock
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Integration Testing & Mocking

Integration tests verify complete user flows by running the full app on a real device or emulator. They test that all screens, navigation, services, and widgets work together correctly from start to finish. Mocking is a technique used in both unit and widget tests where you replace real dependencies like API services or databases with fake implementations that return controlled data. This isolates the code under test so failures point to the exact component that broke. The combination of integration tests for end-to-end verification and mocking for isolated testing gives you comprehensive coverage of your entire app.

dart
1// ── MOCKING with Mockito ──
2// pubspec.yaml (dev_dependencies):
3// mockito: ^5.4.0
4// build_runner: ^2.4.0
5
6import 'package:mockito/annotations.dart';
7import 'package:mockito/mockito.dart';
8
9// Generate mock
10@GenerateMocks([ApiService])
11import 'api_test.mocks.dart'; // generated by build_runner
12
13void main() {
14 late MockApiService mockApi;
15 late ProductRepository repository;
16
17 setUp(() {
18 mockApi = MockApiService();
19 repository = ProductRepository(mockApi);
20 });
21
22 test('getProducts returns list from API', () async {
23 // Arrange: define mock behavior
24 when(mockApi.fetchProducts()).thenAnswer(
25 (_) async => [Product(id: '1', name: 'Widget', price: 9.99)],
26 );
27
28 // Act
29 final products = await repository.getProducts();
30
31 // Assert
32 expect(products.length, 1);
33 expect(products[0].name, 'Widget');
34 verify(mockApi.fetchProducts()).called(1); // verify it was called
35 });
36
37 test('getProducts handles API failure', () async {
38 when(mockApi.fetchProducts()).thenThrow(Exception('No internet'));
39
40 expect(
41 () => repository.getProducts(),
42 throwsA(isA<Exception>()),
43 );
44 });
45}
46
47// ── INTEGRATION TEST ──
48// integration_test/app_test.dart
49import 'package:integration_test/integration_test.dart';
50
51void main() {
52 IntegrationTestWidgetsFlutterBinding.ensureInitialized();
53
54 testWidgets('Full login flow', (tester) async {
55 await tester.pumpWidget(const MyApp());
56 await tester.pumpAndSettle();
57
58 await tester.enterText(find.byKey(Key('email')), 'test@email.com');
59 await tester.enterText(find.byKey(Key('password')), 'password123');
60 await tester.tap(find.byKey(Key('loginButton')));
61 await tester.pumpAndSettle();
62
63 expect(find.text('Welcome'), findsOneWidget);
64 });
65}

AAA Pattern

💡 AAA Pattern

Structure every test with the Arrange-Act-Assert pattern. Arrange sets up mocks, test data, and the object under test. Act calls the method or function you are testing. Assert uses expect() to verify the result matches your expectations. This pattern makes tests consistent, readable, and easy to debug when they fail.

Choosing What To Mock

Mock only external boundaries and unstable dependencies:

  • Network clients, databases, analytics, and platform channels.
  • Keep pure business logic real whenever possible.
  • Prefer lightweight fakes for simple deterministic collaborators.
  • Verify interaction contracts only when behavior depends on call count or order.

Over-mocking makes tests brittle; under-mocking makes tests slow and noisy.

Integration Testing Pipeline Checklist

  • Critical user journeys have at least one end-to-end integration test.
  • Unit and widget tests cover branch logic before integration stage.
  • Test fixtures are deterministic and isolated per run.
  • Mock behavior mirrors real error codes and response shapes.
  • CI distinguishes flaky infra failures from product regressions.

This Lesson In Simple Words

Test app flows end to end and mock dependencies. Testing verifies behavior, and debugging helps you find why behavior is wrong.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Write a test immediately after fixing a bug so it never returns silently.

Deep Understanding Guide

Why this lesson matters

Reliable apps come from repeatable checks, not only manual tapping and visual inspection.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Treat stack traces as maps: locate source, isolate cause, verify fix with tests.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Writing tests only for happy paths and skipping error scenarios.
  • Asserting vague UI text while ignoring behavior expectations.
  • Debugging by random edits instead of reproducing issue consistently.
  • Not separating unit, widget, and integration test responsibilities.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write one unit test, one widget test, and one integration scenario for a feature.
  • Capture a failing state, fix it, and add regression test coverage.
  • Use DevTools to inspect rebuild counts for one interactive screen.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does when().thenAnswer() do in Mockito?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Testable design naturally promotes separation of concerns and lower coupling.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Integration Testing & Mocking" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Writing tests only for happy paths and skipping error scenarios.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does when().thenAnswer() do in Mockito?

when(mock.method()).thenAnswer() stubs the mock to return a specific value when that method is called.

What is the difference between widget tests and integration tests?

Integration tests run the full app on a real device/emulator, testing complete user flows.

What does verify(mock.method()).called(1) check?

verify().called(n) asserts the mocked method was invoked exactly n times during the test.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue