Sub topic 11
Testing API code without a network
This chapter assumes you can write a Dart class with named parameters, use async/await, and add a package to pubspec.yaml. It also assumes you have a fetchPost function that takes an http.Client, as built earlier in this tutorial. Here you will test that code without touching the real network.
Why tests should not use the network
A test that calls a live server fails for reasons unrelated to your code. The server may be down, the device may be offline, or the response may change. Network tests are also slow, and you cannot make a server return a 500 error on demand.
The fix is to replace the network with a fake. The http package supports this because every request goes through an http.Client. If your code receives the client as a parameter instead of creating it inside, a test can pass in a fake client.
This is why fetchPost takes a client argument:
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>);
}Passing the dependency in from outside is called dependency injection. In production you pass http.Client(). In tests you pass a MockClient.
Setting up MockClient
MockClient ships inside the http package, in a separate library. You import it from package:http/testing.dart. No extra dependency is needed beyond http itself and flutter_test.
dependencies:
http: ^1.2.0
dev_dependencies:
flutter_test:
sdk: flutterA MockClient takes a handler function. The handler receives each http.Request and returns a Future<http.Response>. Whatever the handler returns is what your code sees as the server's reply.
A first test
This test checks two things: that the code requests the right path, and that it parses the body into a Post.
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
void main() {
test('fetchPost parses the response body', () async {
final client = MockClient((request) async {
expect(request.url.path, '/posts/1');
return http.Response('{"id": 1, "title": "hello"}', 200);
});
final post = await fetchPost(client, 1);
expect(post.id, 1);
expect(post.title, 'hello');
});
}Run it with flutter test. The test never opens a socket. The handler runs in place of the network call.
The expect inside the handler is an assertion about the outgoing request. If the code asked for /posts/2, the test would fail inside the handler. This is the main way to verify what your code sends.
What a request lets you inspect
The request object that the handler receives describes everything your code sent. These properties are the ones you will check most often.
| Property | What it tells you |
|---|---|
| `request.method` | The HTTP method, such as `GET` or `POST` |
| `request.url` | The full `Uri`, including `path` and `queryParameters` |
| `request.headers` | A map of header names to values |
| `request.body` | The body as a `String` (on `http.Request`) |
| `request.bodyBytes` | The body as raw bytes |
Use these to confirm that headers such as Authorization are attached, or that a query parameter is spelled correctly.
Testing a POST request
For a POST you want to check the method, the Content-Type header, and the encoded body. Then you return a 201 response.
Future<Post> createPost(http.Client client, String title) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts');
final response = await client.post(
uri,
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode({'title': title}),
);
if (response.statusCode != 201) {
throw Exception('Failed to create post: ${response.statusCode}');
}
return Post.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
void main() {
test('createPost sends JSON and parses the 201 reply', () async {
late http.Request captured;
final client = MockClient((request) async {
captured = request;
return http.Response('{"id": 101, "title": "new"}', 201);
});
final post = await createPost(client, 'new');
expect(captured.method, 'POST');
expect(captured.headers['Content-Type'], contains('application/json'));
expect(jsonDecode(captured.body), {'title': 'new'});
expect(post.id, 101);
});
}The handler stores the request in a variable so the test can inspect it after the call. Decoding captured.body and comparing it to a map is safer than comparing raw strings, because key order and spacing do not matter.
Testing failure paths
The real value of a fake client is that you can produce failures at will. The getChecked helper from the error-handling chapter converts non-2xx statuses, timeouts and connection problems into ApiException.
import 'dart:async';
import 'package:http/http.dart' as http;
class ApiException implements Exception {
const ApiException(this.message, {this.statusCode});
final String message;
final int? statusCode;
@override
String toString() => 'ApiException($statusCode): $message';
}
Future<http.Response> getChecked(http.Client client, Uri uri) async {
try {
final response = await client.get(uri).timeout(const Duration(seconds: 10));
if (response.statusCode >= 200 && response.statusCode < 300) {
return response;
}
throw ApiException('Request failed', statusCode: response.statusCode);
} on TimeoutException {
throw const ApiException('The request timed out');
} on http.ClientException catch (e) {
throw ApiException('Connection problem: ${e.message}');
}
}Each branch can be driven by a different handler.
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
void main() {
final uri = Uri.https('example.com', '/data');
test('returns the response for a 200', () async {
final client = MockClient((_) async => http.Response('ok', 200));
final response = await getChecked(client, uri);
expect(response.body, 'ok');
});
test('throws ApiException with the status code for a 404', () async {
final client = MockClient((_) async => http.Response('missing', 404));
expect(
() => getChecked(client, uri),
throwsA(
isA<ApiException>().having((e) => e.statusCode, 'statusCode', 404),
),
);
});
test('wraps a connection failure', () async {
final client = MockClient(
(_) async => throw http.ClientException('no route to host'),
);
expect(
() => getChecked(client, uri),
throwsA(
isA<ApiException>().having(
(e) => e.message,
'message',
contains('Connection problem'),
),
),
);
});
}Notes on this test file:
isA<ApiException>().having(...)checks both the type and one field of the exception.- Pass a function (
() => getChecked(...)) toexpectwiththrowsA. Passing the already-started future also works for async code, but the function form is the usual pattern. - The handler can throw. A thrown
http.ClientExceptionsimulates a lost connection with no server involved.
Simulating a timeout
A timeout test must not wait ten real seconds. You have two options.
- Make the handler return a future that never completes, and use a short timeout in the code under test. This requires the timeout to be a parameter.
- Make the handler throw
TimeoutExceptiondirectly, which exercises theon TimeoutExceptionbranch immediately.
test('maps a timeout to ApiException', () async {
final client = MockClient(
(_) async => throw TimeoutException('too slow'),
);
expect(
() => getChecked(client, Uri.https('example.com', '/data')),
throwsA(
isA<ApiException>().having((e) => e.message, 'message', contains('timed out')),
),
);
});This test needs import 'dart:async'; for TimeoutException. Option 2 checks your error mapping, not the timeout call itself. That is usually what you want, since Future.timeout is part of Dart and does not need testing.
Testing bad data
A server can return a 200 with a body that does not match your model. Your parsing code should fail in a predictable way. Test this too.
test('fetchPost fails on a body with a missing field', () async {
final client = MockClient(
(_) async => http.Response('{"id": 1}', 200),
);
expect(() => fetchPost(client, 1), throwsA(isA<TypeError>()));
});Here json['title'] as String receives null, so the cast throws a TypeError. If you later wrap parsing in a custom exception, update this test to match. A test like this documents the behavior you have chosen.
Multiple responses and call counts
Some code makes several requests, such as a retry loop. The handler can keep state in a local variable.
test('retry succeeds on the second attempt', () async {
var calls = 0;
final client = MockClient((request) async {
calls++;
if (calls == 1) {
return http.Response('busy', 503);
}
return http.Response('{"id": 1, "title": "hello"}', 200);
});
// Replace with your own retry wrapper.
Future<http.Response> getWithRetry() async {
var response = await client.get(Uri.https('example.com', '/posts/1'));
if (response.statusCode == 503) {
response = await client.get(Uri.https('example.com', '/posts/1'));
}
return response;
}
final response = await getWithRetry();
expect(calls, 2);
expect(response.statusCode, 200);
});Asserting on calls confirms that the code retried exactly once and did not hammer the server.
Testing a widget that uses the client
PostScreen receives its client through the constructor, so a widget test can inject a MockClient too. Pump the widget, check the loading state, then settle and check the data.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
void main() {
testWidgets('PostScreen shows the post title', (tester) async {
final client = MockClient(
(_) async => http.Response('{"id": 1, "title": "hello"}', 200),
);
await tester.pumpWidget(
MaterialApp(home: Scaffold(body: PostScreen(client: client))),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('hello'), findsOneWidget);
});
}The first frame shows the spinner because the future has not completed. pumpAndSettle advances frames until the future resolves and the widget rebuilds.
Common mistakes
- Creating the client inside the function. If
fetchPostcallshttp.Client()itself, you cannot replace it. Always accept the client as a parameter or constructor argument. - Putting
expectonly in the handler. If the code never makes the request, the handler never runs and the assertion is silently skipped. Also assert on the result, or count calls. - Using
http.getdirectly. The top-level functions such ashttp.getcreate their own client and bypass your injection. Callclient.getinstead. - Forgetting the
Content-Typeheader in a response with non-ASCII text.http.Responseencodes the body as Latin-1 unless a charset says otherwise. Usehttp.Response.bytes(utf8.encode(body), 200, headers: {'content-type': 'application/json; charset=utf-8'})when the body contains characters outside Latin-1. - Closing a shared client in one test. Create a fresh
MockClientper test so state does not leak.
What MockClient does not cover
MockClient tests your code's logic: request building, parsing and error mapping. It does not check TLS, real timeouts, redirects, or whether the server contract has changed. For that, add a small number of integration tests against a staging server, run separately from your fast unit tests.
Exercise
You wrote getChecked and want to test that a 500 response throws an ApiException whose statusCode is 500. Write the MockClient and the expect call, and explain why the client is created in the test instead of inside getChecked.
Show answer
Use final client = MockClient((_) async => http.Response('boom', 500)); and then expect(() => getChecked(client, uri), throwsA(isA<ApiException>().having((e) => e.statusCode, 'statusCode', 500)));. The client is created in the test and passed in because getChecked accepts it as a parameter. This injection lets the test substitute a fake that returns a canned 500 without any network access.
Exercise
A teammate writes a test where the MockClient handler contains expect(request.url.path, '/posts/1'), but the code under test has a bug and never sends a request. The test passes. Why, and how do you fix it?
Show answer
The handler only runs when a request is made, so with no request the expect never executes. Fix it by also asserting on the outcome, for example checking the returned value, or by counting calls in a variable and asserting calls == 1 after the function returns.