What does when().thenAnswer() do in Mockito?
when(mock.method()).thenAnswer() stubs the mock to return a specific value when that method is called.
Test app flows end-to-end and mock dependencies
You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.
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 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.
1// ── MOCKING with Mockito ──2// pubspec.yaml (dev_dependencies):3// mockito: ^5.4.04// build_runner: ^2.4.056import 'package:mockito/annotations.dart';7import 'package:mockito/mockito.dart';89// Generate mock10@GenerateMocks([ApiService])11import 'api_test.mocks.dart'; // generated by build_runner1213void main() {14late MockApiService mockApi;15late ProductRepository repository;1617setUp(() {18mockApi = MockApiService();19repository = ProductRepository(mockApi);20});2122test('getProducts returns list from API', () async {23// Arrange: define mock behavior24when(mockApi.fetchProducts()).thenAnswer(25(_) async => [Product(id: '1', name: 'Widget', price: 9.99)],26);2728// Act29final products = await repository.getProducts();3031// Assert32expect(products.length, 1);33expect(products[0].name, 'Widget');34verify(mockApi.fetchProducts()).called(1); // verify it was called35});3637test('getProducts handles API failure', () async {38when(mockApi.fetchProducts()).thenThrow(Exception('No internet'));3940expect(41() => repository.getProducts(),42throwsA(isA<Exception>()),43);44});45}4647// ── INTEGRATION TEST ──48// integration_test/app_test.dart49import 'package:integration_test/integration_test.dart';5051void main() {52IntegrationTestWidgetsFlutterBinding.ensureInitialized();5354testWidgets('Full login flow', (tester) async {55await tester.pumpWidget(const MyApp());56await tester.pumpAndSettle();5758await tester.enterText(find.byKey(Key('email')), 'test@email.com');59await tester.enterText(find.byKey(Key('password')), 'password123');60await tester.tap(find.byKey(Key('loginButton')));61await tester.pumpAndSettle();6263expect(find.text('Welcome'), findsOneWidget);64});65}
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.
Mock only external boundaries and unstable dependencies:
Over-mocking makes tests brittle; under-mocking makes tests slow and noisy.
Test app flows end to end and mock dependencies. Testing verifies behavior, and debugging helps you find why behavior is wrong.
Think in architecture, reliability, and team-level maintainability.
Write a test immediately after fixing a bug so it never returns silently.
Reliable apps come from repeatable checks, not only manual tapping and visual inspection.
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.
when(mock.method()).thenAnswer() stubs the mock to return a specific value when that method is called.
Integration tests run the full app on a real device/emulator, testing complete user flows.
verify().called(n) asserts the mocked method was invoked exactly n times during the test.
Something seems incorrect, unclear, or missing? Let us know.
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