How to Mock Dependencies in Flutter Testing

Tutorial 4 of 5

Flutter Testing: How to Mock Dependencies

Introduction

The goal of this tutorial is to impart knowledge on how to mock dependencies in Flutter testing. This tutorial will teach you how to create mock versions of your code's dependencies, enabling more isolated and controlled tests.

By the end of this tutorial, you'll learn:
- What Mocking Dependencies is and why it's important
- How to use mockito package to mock dependencies
- How to write tests using mocked dependencies

Prerequisites:
- Basic understanding of Flutter and Dart
- Familiarity with unit testing in Flutter

Step-by-Step Guide

Before we start, ensure you have mockito package installed in your Flutter project. If not, add the following to your pubspec.yaml file:

dev_dependencies:
  mockito: ^5.0.0

Then, run flutter pub get to install the package.

Mocking Dependencies

Mocking is a technique in testing where real objects are substituted with fake objects that simulate the behavior of the real ones. This is done to isolate the code under test and ensure that the test only tests the code of interest and not its dependencies.

In Flutter, we often use the mockito package to create these fake objects (mocks).

Let's consider we're testing a service that fetches data from an API.

class ApiService {
  Future<String> fetchData() {
    // Code to fetch data from an API
  }
}

We can create a mock for this service using Mockito:

import 'package:mockito/mockito.dart';

class MockApiService extends Mock implements ApiService {}

Now we have a MockApiService that we can use in our tests.

Code Examples

Here is an example of how to use the mocked service in a test.

void main() {
  // Create the mock
  final mockApiService = MockApiService();

  test('Fetches data successfully', () async {
    // Arrange: Set up the mock to return a specific value when called
    when(mockApiService.fetchData())
        .thenAnswer((_) async => 'Mocked data');

    // Act: Call the function you want to test
    var result = await mockApiService.fetchData();

    // Assert: Check that the result is what you expect
    expect(result, 'Mocked data');
  });
}

This test will pass because when fetchData is called on mockApiService, it returns 'Mocked data' as we arranged.

Summary

In this tutorial, you learned about Mocking Dependencies in Flutter Testing. You learned how to use the mockito package to create mocks of your classes and how to use these mocks in tests.

Next, you can learn about more advanced topics in testing like using mockito to mock Streams and Futures, or how to mock dependencies in widget tests.

Practice Exercises

  1. Write a test for a function that throws an error.
  2. Mock the function to throw an error using when().thenThrow()
  3. Use expectLater and throwsA to check that the function throws the expected error.

  4. Write a test for a function that returns a Future.

  5. Mock the function to return a Future using when().thenAnswer((_) async => value)
  6. Use expectLater, completion, and equals to check that the function returns the expected value.

Conclusion

By now, you should have a basic understanding of how to mock dependencies in Flutter testing. Practice is key to understanding, so be sure to try out the practice exercises. Happy testing!