Skip to main content

Flutter Unit Testing with Mockito: Complete Guide with Examples

Flutter Unit Testing with Mockito: Complete Guide with Examples

Learn how to mock dependencies, test business logic, verify API calls, and write reliable Flutter unit tests using Dart and Mockito.

Beginner to Intermediate

Category: Flutter Development | Reading time: 10–15 minutes

Writing tests is an important part of building reliable Flutter applications. Unit tests help developers find bugs early, validate business logic, and make changes with greater confidence.

In this tutorial, we will learn how to write unit tests in Flutter using Mockito. We will start with a simple example and gradually test asynchronous methods, repositories, successful responses, and errors.

What you will learn
  • The difference between unit, widget, and integration tests.
  • How Mockito mocks dependencies.
  • How to use when(), thenReturn(), thenAnswer(), and verify().
  • How to test asynchronous repository methods.
  • How to test success and failure scenarios.
  • How to run tests and troubleshoot common errors.

Table of Contents

  1. Why unit testing matters
  2. Types of Flutter tests
  3. Set up Mockito
  4. Understand the testing architecture
  5. Write your first unit test
  6. Mock dependencies with Mockito
  7. Test asynchronous methods
  8. Test a repository
  9. Test errors and edge cases
  10. Run and debug tests
  11. Best practices
  12. Frequently asked questions

1. Why Is Unit Testing Important in Flutter?

A unit test checks a small, isolated piece of code, such as a function, class, or business rule. It verifies that the code behaves as expected for specific inputs.

✓

Find bugs early

Catch logic problems before they reach users.

⚙

Safer refactoring

Change implementations while checking existing behavior.

⚡

Fast feedback

Run focused tests without launching the complete app.

For example, suppose your application calculates a discount, validates a payment amount, or decides whether a user is eligible for a feature. Unit tests can verify those rules without requiring a real server or database.

2. Types of Tests in Flutter

Flutter Testing Strategy
↓
Unit tests

Functions and business logic

Widget tests

UI and interactions

Integration tests

Complete application flows

Unit tests focus on isolated logic. Widget tests verify that widgets render and respond correctly. Integration tests validate interactions across larger parts of an application, potentially running on a device or emulator.

Mockito is particularly useful for unit tests because it allows you to replace dependencies with controlled test doubles.

3. Set Up Mockito in Your Flutter Project

Create a Flutter project if you do not already have one:

flutter create flutter_mockito_demo
cd flutter_mockito_demo

Add the testing dependencies:

flutter pub add --dev mockito
flutter pub add --dev build_runner

Flutter projects already include the flutter_test package in their development dependencies by default.

Mockito generates mock classes for dependencies. We will use the @GenerateMocks annotation and build_runner to generate a mock class from an abstract interface.

Suggested project structure

lib/
  services/
    calculator_service.dart
  repositories/
    user_repository.dart

test/
  calculator_service_test.dart
  user_repository_test.dart

4. Understand How Mockito Works

Imagine that a class depends on another class. Instead of using the real dependency during a test, we provide a mock that returns predefined results.

Unit Under Test
↓ calls dependency
Mockito Mock
↓ predefined response
Test verifies expected behavior

This approach keeps unit tests predictable. You do not need a live backend, production credentials, or an internet connection to test the business logic that depends on a mock.

5. Write Your First Flutter Unit Test

Let's begin with a simple calculator service. This demonstrates the basic structure of a test before introducing mocks.

Create lib/services/calculator_service.dart:

class CalculatorService {
  int add(int a, int b) {
    return a + b;
  }

  int multiply(int a, int b) {
    return a * b;
  }
}

Create test/calculator_service_test.dart:

import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_mockito_demo/services/calculator_service.dart';

void main() {
  group('CalculatorService', () {
    late CalculatorService calculator;

    setUp(() {
      calculator = CalculatorService();
    });

    test('adds two numbers', () {
      expect(calculator.add(2, 3), 5);
    });

    test('multiplies two numbers', () {
      expect(calculator.multiply(4, 3), 12);
    });

    test('handles negative numbers', () {
      expect(calculator.add(-2, 5), 3);
    });
  });
}

Replace flutter_mockito_demo in the import with your actual package name if it differs.

Understanding the test functions

  • group() organizes related tests.
  • setUp() runs before each test in the group.
  • test() defines an individual test case.
  • expect() compares the actual result with the expected value.

Notice that this first example does not need Mockito. Mocking becomes valuable when a class depends on another service, repository, database, or network client.

6. Mock Dependencies with Mockito

Suppose a user service depends on a repository. We want to test the service without accessing a real database or API.

First, create lib/repositories/user_repository.dart:

abstract class UserRepository {
  Future<String> getUserName(int id);
}

class UserService {
  UserService(this.repository);

  final UserRepository repository;

  Future<String> getWelcomeMessage(int id) async {
    final name = await repository.getUserName(id);
    return 'Welcome, $name!';
  }
}

Now create test/user_repository_test.dart:

import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';

import 'package:flutter_mockito_demo/repositories/user_repository.dart';

import 'user_repository_test.mocks.dart';

@GenerateMocks([UserRepository])
void main() {
  late MockUserRepository mockRepository;
  late UserService userService;

  setUp(() {
    mockRepository = MockUserRepository();
    userService = UserService(mockRepository);
  });

  test('returns a welcome message', () async {
    when(mockRepository.getUserName(1))
        .thenAnswer((_) async => 'Alex');

    final result = await userService.getWelcomeMessage(1);

    expect(result, 'Welcome, Alex!');
    verify(mockRepository.getUserName(1)).called(1);
  });
}

Generate the mock class with:

dart run build_runner build --delete-conflicting-outputs

Build_runner generates user_repository_test.mocks.dart. This generated file should not be edited manually.

Key Mockito methods
  • when() defines the expected behavior of a mock.
  • thenAnswer() provides a response, including an asynchronous response.
  • verify() checks whether a method was called.
  • called(1) asserts that the method was called once.

7. Test Asynchronous Methods

Flutter applications frequently use asynchronous operations for APIs, local storage, and database queries. Mockito can provide controlled Future responses for these methods.

For example, a successful asynchronous mock can be configured as follows:

when(mockRepository.getUserName(2))
    .thenAnswer((_) async => 'Sam');

final result = await userService.getWelcomeMessage(2);

expect(result, 'Welcome, Sam!');

To simulate a failure, use a failed Future:

when(mockRepository.getUserName(3))
    .thenAnswer(
      (_) async => Future<String>.error(
        Exception('Server unavailable'),
      ),
    );

Because UserService currently allows exceptions to propagate, the caller will receive the error. In a real application, you might catch expected failures and map them into a domain-specific exception or result type.

8. Test a Repository with Success and Failure Scenarios

A repository often acts as the boundary between business logic and data sources. Good tests should cover both successful results and expected failure behavior.

For the repository in this example, useful cases include:

Test 1: Successful response

Configure the mock to return a username and verify the welcome message.

Test 2: Dependency failure

Return a failed Future and verify that the service propagates or handles the exception as designed.

Test 3: Verify interactions

Use verify() to ensure the expected repository method was called with the correct argument.

Keep each test focused on one behavior. Avoid checking implementation details that do not matter to the class's public contract.

9. Test Error Handling and Edge Cases

Testing only successful scenarios can leave important bugs undiscovered. Consider the following additional cases in your Flutter project:

  • Invalid user IDs.
  • Empty or missing API data.
  • Network timeouts and server errors.
  • Unauthorized API responses.
  • Unexpected JSON values.
  • Repeated calls and dependency interactions.

For example, if your service is expected to propagate a repository exception, you can test it with:

test('propagates repository errors', () async {
  when(mockRepository.getUserName(9))
      .thenAnswer(
        (_) async => Future<String>.error(
          Exception('User not found'),
        ),
      );

  await expectLater(
    userService.getWelcomeMessage(9),
    throwsA(isA<Exception>()),
  );
});

This test checks the current behavior of UserService. If you later change the service to catch and transform exceptions, update the test to match the intended public behavior.

10. Run and Debug Flutter Unit Tests

Run all tests from the project root:

flutter test

Run one specific test file:

flutter test test/calculator_service_test.dart

Regenerate mocks after changing an annotated interface:

dart run build_runner build --delete-conflicting-outputs

Common problems and solutions

Problem Solution
Mock class not found Run build_runner and check the generated file import.
Unexpected null result Stub the relevant method before invoking the class under test.
Async test fails Await the Future or use expectLater for asynchronous assertions.
Mockito cannot mock a dependency Check the annotation, generated code, dependency type, and current Mockito documentation.
Test depends on the internet Mock the API boundary for unit tests and reserve live-server checks for integration tests.

11. Best Practices for Flutter Unit Testing

  1. Keep tests independent. One test should not rely on another test's state.
  2. Use descriptive names. Explain the condition and expected result in the test name.
  3. Mock external dependencies. Replace network clients, databases, and other external services when testing isolated business logic.
  4. Cover failures as well as success. Include invalid inputs and expected exceptions.
  5. Test observable behavior. Focus on results and important interactions rather than private implementation details.
  6. Regenerate generated mocks when necessary. Keep generated files synchronized with their source interfaces.
  7. Run tests in CI. Use automated checks to catch regressions before merging code.

12. Frequently Asked Questions

What is Mockito in Flutter?

Mockito is a Dart mocking library that lets developers create mock dependencies, define their responses, and verify interactions during tests.

Do I need Mockito for every unit test?

No. Simple functions and self-contained classes can be tested directly. Mockito is useful when you need to isolate a class from its dependencies.

What is the difference between when() and verify()?

when() configures a mock's behavior. verify() checks whether a method was called as expected.

What is the difference between thenReturn() and thenAnswer()?

thenReturn() provides a predefined return value. thenAnswer() computes a response from an invocation and is especially useful for asynchronous methods and invocation-specific behavior.

Can Mockito test REST API calls?

Yes. You can mock a repository or API client to test how your business logic responds to successful responses and failures. Separate integration tests can verify the real network configuration and backend contract.

Should I use Mockito or mocktail?

Both are popular Dart mocking options. Mockito uses generated mocks for many common scenarios, while mocktail supports a different, runtime-oriented mocking approach. Choose the library that best fits your team's workflow and project requirements.

Conclusion

Flutter unit testing with Mockito helps developers verify business logic independently from databases, APIs, and other dependencies. By combining descriptive test cases, generated mocks, asynchronous testing, and failure scenarios, you can build a more reliable and maintainable application.

Start with simple unit tests, then introduce mocks when you need to isolate dependencies. As your project grows, integrate your tests into CI/CD so problems are caught early.

Keep learning Flutter

Explore the official testing guides and package documentation to improve your testing workflow.

Flutter Testing Documentation

Official References

Code examples are educational. Verify package versions, generated mock output, and imports against your project's current Dart and Flutter SDK.

Comments

Popular posts from this blog

Designing and Building Dual-Screen Apps for Concept "iPhone Duo" in Flutter

FLUTTER • ADAPTIVE UI • CONCEPT DESIGN Designing and Building Dual-Screen Apps for the Concept “iPhone Duo” in Flutter Explore adaptive layouts, two-pane navigation, simulated dual-screen experiences, and the engineering decisions behind apps designed for two displays. Reading time: 10–12 minutes Concept disclaimer: “iPhone Duo” is used here as a hypothetical dual-screen device concept, not as a claim that Apple has announced or released such a product. Flutter examples in this article demonstrate adaptive and simulated two-pane layouts that can be tested on existing devices. What if an iPhone could provide two displays that work together? Imagine reading an article on one screen while keeping notes on the other, browsing a product list beside its details, or viewing a video while controlling playback on a separate panel. This kind of experience introduces an interesting app-design challenge: the interface must understand how much space is avail...

Dynamic and responsive ListView in flutter

How to create responsive and dynamic Listview? Step 1: Create Listview builder ListView.builder( physics: ScrollPhysics(parent: AlwaysScrollableScrollPhysics()), itemCount: allBillList[ 0 ].data!.length, scrollDirection: Axis.vertical, itemBuilder: (c, index1) { String data = mainList![index1]; return ListItem(data); }) Step 2: Create separate ListItem.dart file import 'package:flutter/cupertino.dart' ; import 'package:flutter/material.dart' ; class ListItem extends StatefulWidget { ListItem({ this .data}); final String? data; @override _ListItemState createState() => _ListItemState(); } class _ListItemState extends State<ListItem> { @override Widget build(BuildContext context) { // TODO: implement build return Column( children: [ Container(margin: const EdgeInsets.all( 16.0 ), child:Text(data)), BasicWidget.getDivider(), ], ); } } So if you want to delete or add items in main...

Flutter Bloc Pattern 9.1.1 Call API

Flutter Architecture Tutorial How to Fetch API Data & Display in ListView Using Flutter BLoC Pattern Build a clean Flutter app that fetches users from a REST API, manages loading and error states with BLoC, and displays results in a ListView. Fetching data from a REST API and displaying it in a scrolling list is one of the most common tasks in Flutter development. As an app grows, keeping network requests, UI code, and state management mixed together can make the code difficult to test and maintain. The BLoC (Business Logic Component) pattern helps separate business logic from the presentation layer. In this tutorial, we’ll build a small example using flutter_bloc , http , and a public sample API. You’ll learn how to handle loading, success, empty, and error states without placing API logic directly inside the widget. What we’ll build Fetch a list of users from a REST endpoint Create a model, repository, BLoC, events, and st...

Building Dual-Screen & Foldable ListView Apps in Flutter using TwoPane

Flutter Tutorial Building Dual-Screen & Foldable ListView Apps in Flutter using TwoPane Learn how to adapt your Flutter layout for dual-screen and foldable devices using Microsoft's dual_screen package and Flutter's TwoPane widget. Dual-screen and foldable mobile devices offer unique screen real estate. Instead of showing a single list view that navigates to a new page, dual-screen layouts allow developers to display a Master-Detail view side-by-side when unfolded or on dual screens, and fall back to a single page view on standard phones. What You Will Learn: Understanding Dual-Screen Hinge and Folding Display Features Implementing the TwoPane widget for responsive multi-screen layouts Handling Master-Detail state selection dynamically Material 3 visual layout standards for adaptive design 1. Step 1: Add Dependencies Add the official dual_screen ...

A Complete Guide to Publishing a Flutter App on the Apple App Store

Flutter • iOS • App Store Connect A Complete Guide to Publishing a Flutter App on the Apple App Store From your first iOS release build to TestFlight, App Review, and a successful App Store launch. Who is this guide for? Flutter developers who have an app ready for iOS distribution. You need a Mac with a compatible version of Xcode and access to the Apple Developer Program. Apple requirements change, so verify current policies before submitting. Publishing workflow at a glance 👤 1. Account Developer Program ⚙️ 2. Configure Bundle ID and signing 📦 3. Build Archive and upload 🚀 4. Release Review and launch 1. Prerequisites Mac and Xcode: iOS builds and signing require macOS and Xcode. Use versions supported by your Flutter SDK and accepted by App Store Connect. Flutter SDK: Use a stable release and check that your plugins support the target iOS version. Apple Developer Program: Enroll if you need App Store distribution. Membership terms and fees depend on your r...
  Implementing Search by Character in Flutter: A Complete Guide with Examples Searching is one of the most common features in mobile applications. Whether you're building a contact list, product catalog, employee directory, or chat application, users expect search results to update instantly as they type. Flutter makes it easy to implement search by character , where the list filters after every keystroke without requiring users to tap a search button. In this guide, you'll learn how to implement a fast, efficient, and scalable character-by-character search in Flutter. What is Search by Character? Search by character (also called live search or incremental search ) filters data every time the user types a new character. For example: User Types Results ---------------------------------------- A Apple, Amazon, Adobe Ap Apple App Apple Appl Apple Apple Apple Instead of waiting for the user to...

How to Write Test Cases in Flutter: A Complete Guide with Examples

Flutter Testing Handbook How to Write Test Cases in Flutter: A Complete Guide with Examples Learn how to write unit, widget, and integration tests in Flutter—with practical Dart examples, testable app structure, and commands you can use in your project. Testing helps you catch bugs early, protect existing features when code changes, and ship Flutter apps with greater confidence. Instead of manually checking every screen after each update, you can automate many checks and run them whenever you change your code. In this guide, we’ll cover the main Flutter testing types, set up a test environment, write examples for business logic and UI, test asynchronous behavior, mock dependencies, and run tests from the command line. What you’ll learn How unit, widget, and integration tests differ How to create and run a Flutter test file How to test validation, calculations, buttons, and displayed text How to handle asynchronous ...

Learn SQLite using flutter

What Is SQLite SQLite is an open source relational database, it is used to create a database, perform different operation like add, delete and remove data. SQLite setup Add the required dependencies. For this article, you’ll need the  sqflite package  for using the SQLite database. Open a simulator device or connect a real device to your system and start the app using the following command: flutter run Add your SQLite file which you want to read and write. Place your file under assets folder like below image Create DBQueries and DBProvider. DBProvider is require to connect your app with database. import 'dart:io' ; import 'package:flutter/services.dart' ; import 'package:path_provider/path_provider.dart' ; import 'package:sqflite/sqflite.dart' ; import 'package:path/path.dart' ; class DBProvider { static final DBProvider _instance = new DBProvider . internal (); factory DBProvider() => _instance ; static Database _database ; Future<...

Manage Firebase storage using flutter

Flutter • Firebase • Mobile Development Manage Firebase Storage Using Flutter A practical, end-to-end guide to uploading, monitoring, listing, downloading, and deleting files securely with Cloud Storage for Firebase. Beginner friendly Working code examples Security rules What you will build: a small Flutter file manager that uploads a selected file, shows upload progress, retrieves its download URL, lists files in a user folder, and deletes a selected file. The examples assume Firebase Authentication is enabled and the user is signed in. 1. What is Firebase Storage? Cloud Storage for Firebase stores user-generated content such as profile pictures, receipts, PDFs, videos, and documents. Flutter communicates with the Firebase Storage SDK; the SDK sends the file to a storage bucket, where Firebase Security Rules decide whether the request is allowed. 📱 Flutter app Selects the file → 🔐 Firebase SDK Checks request access ...

Customised Flutter AppBar

Create centralized AppBar for all screens at one place. In just 2 steps you create your own appBar. 1) Create AppBar.dart here you have to pass true and false to showRight and inside rightWidget pass widget from parent screen.(check step 2) class  AppBarWidget { static getAppBar (String title, [showRight, rightWidget]) { if (showRight == null ) { showRight = false ; } return AppBar ( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. backgroundColor: Colors. white , title: Text ( title, style: TextStyle (color: AppColors. btn_primary_dark_new ,fontWeight: FontWeight. w600 ), ), centerTitle: true , leadingWidth: 100 , leading: Padding ( padding: const EdgeInsetsDirectional . only (start: 8.0 ), child: InkWell ( onTap: () { Get.back(); }, child: Row ( ...