Why Mock API Calls?
Testing parts of your app that talk to online services can be slow and sometimes unreliable. What if the internet is down? What if the server changes? Mocking helps you avoid these problems by simulating real responses.
What is Mocking?
Mocking means creating fake versions of things your code depends on, like an API client. Instead of making a real network request, your code talks to the fake client (the mock). This mock is set up to give back specific, predictable answers.
Using Mocktail for Mocking
The image shows how to use the mocktail
package in Dart/Flutter to mock HttpClient
calls.
Setting up the Mock
You first import the package and create a class that mocks the original service.
import 'package:mocktail/mocktail.dart';
class HttpClientMock extends Mock implements HttpClient {}
Then, you create an instance of your mock:
final httpClientMock = HttpClientMock();
Defining Mock Responses
Simulating a GET Request
You use when
to say "when this specific method is called on the mock...". Then you use thenAnswer
to say "give back this specific result".
when(() => httpClientMock.get(Uri.parse('myapi/ ...')))
.thenAnswer((_) async => Response(
'''
{"id":"testId","route":"myPage"}
''',
200,
));
This code tells the httpClientMock
that when its get
method is called with the URI 'myapi/ ...'
, it should pretend to return a Response
with a status code of 200 and a specific JSON body.
Benefits
Mocking lets you test how your app handles different API responses without needing a real network connection or a running backend server. This makes your tests run faster and gives you more control over test scenarios, including error cases.
Writing tests without mocking
Mocking can be tricky and reflect implementations details when testing. There is actualy a way to test your code without mocking.
Here is a complete article on how to write Flutter test without mocks.