Tillitsdone
down Scroll to discover

Mocking Dependencies in Flutter Test with Mockito

Learn how to effectively use Mockito for testing Flutter applications by mocking dependencies.

Master the art of writing reliable tests that simulate real-world scenarios.
thumbnail

A minimalist abstract representation of interlocking gears and connections rendered in bright cyan and electric blue on a deep black background shot from a top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Mocking Dependencies in Flutter Test with Mockito

Testing is a crucial part of developing robust Flutter applications, but what happens when your code depends on external services, APIs, or complex objects? This is where mocking comes into play, and Mockito is your best friend for handling these scenarios elegantly.

Understanding the Importance of Mocking

In real-world Flutter applications, we often work with dependencies like HTTP clients, databases, or platform-specific services. Testing these dependencies directly can be challenging because:

  • They might be unreliable or slow
  • They could cost money to use
  • They might not be available in a test environment

An abstract network of floating geometric shapes representing data flow featuring emerald green and gold colors against a deep black background captured from a diagonal angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Getting Started with Mockito

First, add the required dependencies to your pubspec.yaml:

dev_dependencies:
mockito: ^5.4.0
build_runner: ^2.4.0

Let’s say we have a simple weather service that fetches the current temperature:

class WeatherService {
final HttpClient client;
WeatherService(this.client);
Future<double> getTemperature(String city) async {
final response = await client.get('api.weather.com/temperature/$city');
return response.data['temperature'];
}
}

To test this service, we’ll create a mock of the HttpClient:

@GenerateMocks([HttpClient])
void main() {
late MockHttpClient mockClient;
late WeatherService weatherService;
setUp(() {
mockClient = MockHttpClient();
weatherService = WeatherService(mockClient);
});
test('should return correct temperature', () async {
// Arrange
when(mockClient.get(any))
.thenAnswer((_) async => Response(data: {'temperature': 25.0}));
// Act
final temperature = await weatherService.getTemperature('London');
// Assert
expect(temperature, 25.0);
verify(mockClient.get('api.weather.com/temperature/London')).called(1);
});
}

Dynamic flowing lines representing code execution paths rendered in bright orange and turquoise colors viewed from a side perspective with depth high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Best Practices for Mocking in Flutter

  1. Mock at the Right Level: Mock at interface boundaries rather than mocking every small class. This makes your tests more maintainable and less brittle.

  2. Verify Behavior: Don’t just test the output – verify that your mocks were called with the expected parameters using verify().

  3. Use Meaningful Responses: When setting up mock responses, use realistic data that represents actual scenarios your app might encounter.

  4. Keep it Simple: Don’t over-mock. If a dependency is simple and reliable (like basic calculations), use the real implementation.

Here’s how to handle more complex scenarios:

test('should handle errors gracefully', () async {
// Arrange
when(mockClient.get(any))
.thenThrow(Exception('Network error'));
// Act & Assert
expect(
() => weatherService.getTemperature('London'),
throwsException,
);
});

Conclusion

Mocking with Mockito is an essential skill for writing effective Flutter tests. It allows you to isolate the code you’re testing, make your tests more reliable, and ensure your app works correctly under various conditions.

Remember, the goal of mocking isn’t to test the mocks themselves, but to verify that your code interacts with its dependencies correctly.

Abstract pattern of interconnected circuits and nodes featuring iridescent silver and azure blue colors flowing through black space captured from a Dutch angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svgicons/flutter.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.