Skip to content
tezvyn:
Menu

Mocking Dependencies in Flutter with Mockito

Source: docs.flutter.devMediumHow cards are made

Mockito creates fake, controllable versions of your app's dependencies, like an API client. This is crucial for unit tests, letting you isolate code from external systems to make tests fast, reliable, and independent of network or database availability.

Why it exists

When you write a unit test, you want to test a single "unit" of code in isolation. However, code rarely lives in isolation. A class that fetches user data might depend on an HTTP client, which in turn depends on the device's network stack. Testing this class directly would mean making a real network call, which is slow, unreliable, and depends on a live server. Mocking was created to solve this by replacing real dependencies with predictable fakes.

The mental model

Think of a mock object as a stunt double for your real dependency. In a movie, you use a stunt double for dangerous or complex scenes to avoid risking the real actor. In testing, you use a mock object (the stunt double) in place of a real dependency like a database or network client (the real actor). You can program this stunt double to perform specific actions on cue, allowing you to safely and predictably test your main code's reaction.

How it works

The mockito package in Dart uses code generation to create a fake version of a class. You first annotate a test file and run a build command, which generates a Mock class. In your test, you instantiate this mock. The key is the when() function: you tell the mock how to behave. For example, you can say, "WHEN your fetchData method is called with the argument '123', THEN return this specific Data object." Your code under test is given this mock instead of the real object. When it calls fetchData('123'), the mock intercepts the call and returns the data you predefined, without ever touching a real database or network.

When to use it

Use mocking extensively in unit tests. It's perfect for isolating your business logic from external systems. If you're testing a repository, a BLoC, a ViewModel, or any class that has dependencies, you should mock those dependencies. This makes your tests fast, deterministic (they produce the same result every time), and focused only on the logic you intend to test.

When not to use it

Do not use mocks for integration tests or end-to-end (e2e) tests. The entire point of those tests is to verify that different parts of your system work together correctly with their real dependencies. Mocking a database connection in an integration test would defeat the purpose. Be wary of over-mocking; if a test requires dozens of mocks to be set up, it might be a sign that your class is doing too much and should be refactored.

One canonical example

Imagine testing a WeatherService that depends on an ApiClient. Instead of letting it make a real HTTP request, you provide a MockApiClient. In your test's setup phase, you would write something like: when(mockApiClient.get(any)).thenAnswer((_) async => '{"temperature": 72}');. You then call your weatherService.getCurrentTemperature() method. You can then verify that your service correctly called the get method on the client and correctly parsed the fake JSON response to return the number 72.

Interview question

What is the primary reason to use Mockito in Flutter unit tests?

  • a.To automate the simulation of user interface interactions and navigation paths.
  • b.To isolate the code under test from its external dependencies, making tests fast and deterministic.Correct
  • c.To confirm that real external services are correctly integrated with the application.
  • d.To generate complete implementations for complex API clients and database access layers.
Why?

Mockito's core purpose is to replace real dependencies with controllable fakes, allowing unit tests to run quickly and reliably in isolation from external systems. Option C describes integration testing, which explicitly avoids mocking to verify real system interactions.

Just read this? Test yourself on what you have been reading.

Read the original → docs.flutter.dev

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on flutter — each one lists the topics its interview covers.

See open roles