Sub topic 11
Testing API Code Without a Network
This chapter assumes you know Dart classes, null safety, Future and async/await, Flutter widget basics, and how to add packages to pubspec.yaml. It also assumes you have a Post model and a fetchPost function that use the http package.
Network tests are slow and unreliable. They can fail because of Wi-Fi, a server outage, or changed test data. A unit test should check your code in isolation. For API code, that means replacing the real network client with a fake client that returns a controlled response.
Use `MockClient` to control the response
The http package provides MockClient through the http/testing.dart library. You give it a callback. The callback receives the outgoing request and returns an http.Response.
This lets one test verify both sides of the exchange:
- The app sends the correct method, URL, headers, and body.
- The app parses a successful or failed response correctly.
The following example assumes fetchPost accepts an http.Client:
Future<Post> fetchPost(http.Client client, int id) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/$id');
final response = await client.get(
uri,
headers: {'Accept': 'application/json'},
);
if (response.statusCode != 200) {
throw Exception('Failed to load post: ${response.statusCode}');
}
return Post.fromJson(
jsonDecode(response.body) as Map<String, dynamic>,
);
}A test can provide a MockClient instead of making a real request:
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:my_app/api.dart';
void main() {
test('fetchPost parses a successful response', () async {
final client = MockClient((request) async {
expect(request.method, 'GET');
expect(request.url.path, '/posts/1');
expect(request.headers['accept'], 'application/json');
return http.Response(
'{"id": 1, "title": "hello"}',
200,
headers: {'content-type': 'application/json'},
);
});
final post = await fetchPost(client, 1);
expect(post.id, 1);
expect(post.title, 'hello');
});
}The callback is asynchronous because a real HTTP request is asynchronous. The test still runs entirely locally.
Test failures and request bodies
A useful test suite covers more than successful JSON. Return an error status to check that your API function throws:
test('fetchPost rejects a server error', () async {
final client = MockClient((request) async {
return http.Response('Internal error', 500);
});
expect(
() => fetchPost(client, 1),
throwsA(isA<Exception>()),
);
});For a POST request, inspect the request body before returning a response:
test('createPost sends JSON', () async {
final client = MockClient((request) async {
expect(request.method, 'POST');
expect(request.headers['content-type'], contains('application/json'));
expect(request.body, '{"title":"new post"}');
return http.Response(
'{"id": 2, "title": "new post"}',
201,
);
});
final post = await createPost(client, 'new post');
expect(post.id, 2);
});Comparing the exact body works when the JSON has a stable field order. For more flexible tests, decode request.body and compare the resulting map.
Test one behavior at a time
A focused test has one reason to fail. Useful cases include:
| Behavior | Controlled input | Expected result |
|---|---|---|
| Successful GET | `200` with valid JSON | Typed model |
| Server failure | `500` response | Exception |
| Invalid data | Malformed JSON | Parsing error |
| POST request | Canned `201` response | Correct method and body |
If your API layer converts timeouts and connection failures into ApiException, make the mock throw the same lower-level exception and verify the conversion. This keeps error handling testable without waiting for a real timeout.
Exercise
Why should an API function accept an http.Client instead of creating a client internally?
Show answer
Dependency injection lets production code use a real client while tests provide a MockClient. The test can control responses and verify requests without using a network.