Mock the SellerMagnet API in Dart tests by faking only http.Client, never your own client module: package:http's own MockClient (from http/testing.dart) replaces the one call the real sellermagnet.dart and retry.dart helpers make, scripts the status code and body each test needs, and runs the unchanged client code against it with the test package. No network call leaves the test, no credit is spent, and the exact parsing and retry logic under test is the code that ships.
Key Takeaways
- Fake
http.Client, not your own client module; MockClient already ships in package:http so there is no hand-written mock to drift from the real request. - Make the fake fail closed: build the default client with a MockClient that throws, and have every test build its own from install(route) instead of letting an unconfigured call through.
- A 429 is free and worth waiting out; a 500 is refunded and worth one retry; a 502/503 is billed on every attempt, so the retry loop caps its attempts.
- This suite does not fake the clock: the 429/500/502 tests really wait out the backoff, the same way the Node.js and Go mock-testing guides do.
- Count every call the fake received (
mockApi.calls.length) to verify the credit math of a scenario, not just its final return value.
Why not just call the real API in a Dart test suite?
Every SellerMagnet API request is billed per the table below, whether it comes from production code or a test. A CI run that fires on every push would spend credits on every build, a slow or flaky network turns a code bug into a failed pipeline, and a 404 or a 429 that a test wants to simulate on demand cannot be forced on the live API at all. A fake http.Client makes every status code, including ones that are rare in practice, reproducible on every run.
| Scenario | Charged | Retry? | Client should |
|---|---|---|---|
| happy path lookup | billed | no | parse, 1 credit |
| 404 product not found | billed | no | report it; do not retry |
| free gate 400 (missing marketplaceId) | free | no | fix the request, no retry |
| 401 insufficient credits | free | no | stop; top up credits |
| 429 concurrency cap | free | yes | wait Retry-After, then retry |
| 500 internal error | refunded | yes | retry once, then stop |
| 502 / 503 upstream | billed | yes | retry up to the attempt cap |
How do I fake just http.Client, not my own code?
Build an http.Client with package:http's MockClient (http/testing.dart), whose handler reads the request, returns a scripted http.Response, and let sellermagnet.dart's get() and retry.dart's getWithRetry() run exactly as they would in production, since both functions take the client as a parameter instead of constructing their own. The default client throws a StateError on every call, so a test that forgets to call install() fails loudly instead of letting a real, billed request through. api_key travels as a query parameter here, the same transport the Dart quickstart uses; the fake asserts it is present on every call.

sellermagnet.dart - the real client under test, unmodified by the mock
// sellermagnet.dart - the real client under test, unmodified by the mock.
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
const _api = 'https://sellermagnet-api.com/api';
class ApiError implements Exception {
final int status;
final String message;
final int retryAfter;
ApiError(this.status, this.message, [this.retryAfter = 0]);
@override
String toString() => 'ApiError($status: $message)';
}
class Product {
final String asin;
final String title;
final double? price; // "N/A" or missing must become null, never 0
final String? currency;
final int? rank;
final String url;
Product({
required this.asin,
required this.title,
required this.price,
required this.currency,
required this.rank,
required this.url,
});
}
Future<Map<String, dynamic>> get(http.Client client, String endpoint, Map<String, String> params) async {
final apiKey = Platform.environment['SELLERMAGNET_API_KEY'];
if (apiKey == null || apiKey.isEmpty) {
throw StateError('Set SELLERMAGNET_API_KEY first');
}
final query = {...params, 'api_key': apiKey};
final uri = Uri.parse('$_api/$endpoint').replace(queryParameters: query);
final res = await client.get(uri).timeout(const Duration(seconds: 120));
Map<String, dynamic> body;
try {
final decoded = jsonDecode(res.body);
body = decoded is Map<String, dynamic> ? decoded : const {};
} on FormatException {
body = const {}; // an HTML error page is not JSON
}
if (res.statusCode >= 200 && res.statusCode < 300 && body['success'] == true) {
return body['data'] as Map<String, dynamic>;
}
final retryAfter = int.tryParse(res.headers['retry-after'] ?? '') ?? 0;
throw ApiError(res.statusCode, (body['message'] as String?) ?? 'request failed', retryAfter);
}
Future<Product> lookup(http.Client client, String asin, String marketplaceId) async {
final data = await get(client, 'amazon-product-lookup', {'asin': asin, 'marketplaceId': marketplaceId});
final p = data['productInfo'] as Map<String, dynamic>;
final buyBox = p['buyBoxInfo'] as Map<String, dynamic>?;
final priceRaw = buyBox == null ? null : buyBox['price'];
final ranks = p['bestsellerRanks'] as Map<String, dynamic>?;
final mainCategory = ranks == null ? null : ranks['main_category'] as Map<String, dynamic>?;
return Product(
asin: p['asin'] as String,
title: p['title'] as String,
price: priceRaw is num ? priceRaw.toDouble() : null,
currency: buyBox == null ? null : buyBox['currencyCode'] as String?,
rank: mainCategory == null ? null : mainCategory['rank'] as int?,
url: p['link'] as String,
);
}
retry.dart - the real retry wrapper under test, unmodified by the mock
// retry.dart - the real retry wrapper under test, unmodified by the mock.
import 'package:http/http.dart' as http;
import 'sellermagnet.dart';
const _retryable = {429, 500, 502, 503};
Future<Map<String, dynamic>> getWithRetry(
http.Client client,
String endpoint,
Map<String, String> params, {
int attempts = 4,
}) async {
var internalErrors = 0;
for (var attempt = 1; attempt <= attempts; attempt++) {
try {
return await get(client, endpoint, params);
} on ApiError catch (err) {
if (err.status == 500) internalErrors += 1;
if (!_retryable.contains(err.status) || attempt == attempts || internalErrors > 1) rethrow;
final backoff = 1 << attempt; // 2, 4, 8, 16 seconds
final wait = backoff > err.retryAfter ? backoff : err.retryAfter;
await Future<void>.delayed(Duration(seconds: wait > 30 ? 30 : wait));
}
}
throw StateError('unreachable'); // attempts is always >= 1
}
mock_api.dart - fakes only http.Client via package:http's own MockClient, fails closed
// mock_api.dart - fakes only the HTTP layer via http's own MockClient.
// sellermagnet.dart / retry.dart run completely unmodified. Fails closed:
// a client built with blocked() throws on every call until install(route) replaces it.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
/// One scripted response: either a decoded JSON body, or (for the "html error
/// page" scenario) raw text that is not valid JSON at all.
class RouteResponse {
final int status;
final Map<String, dynamic>? body;
final String? rawBody;
final Map<String, String> headers;
const RouteResponse(this.status, this.body, {this.headers = const {}}) : rawBody = null;
const RouteResponse.html(this.status, this.rawBody) : body = null, headers = const {};
}
typedef Route = RouteResponse Function(String endpoint, Map<String, String> params);
/// Every call the fake received: (endpoint, query parameters).
final List<MapEntry<String, Map<String, String>>> calls = [];
RouteResponse ok(Map<String, dynamic> data) => RouteResponse(200, {'success': true, 'data': data});
RouteResponse err(int status, [String message = 'request failed', Map<String, String> headers = const {}]) =>
RouteResponse(status, {'success': false, 'error': 'error', 'message': message}, headers: headers);
/// Builds a client whose every GET is answered by [route]. Clears the call
/// log so each test starts from zero.
http.Client install(Route route) {
calls.clear();
return http_testing.MockClient((request) async {
final params = request.url.queryParameters;
if (!params.containsKey('api_key')) {
throw StateError('mock_api: api_key must travel as a query parameter');
}
final endpoint = request.url.pathSegments.last;
calls.add(MapEntry(endpoint, params));
final res = route(endpoint, params);
final text = res.rawBody ?? jsonEncode(res.body);
return http.Response(text, res.status, headers: res.headers);
});
}
/// The default client before any test calls install(): fails closed.
http.Client blocked() => http_testing.MockClient((request) async {
throw StateError('mock_api: call install(route) first - no request may reach the real API');
});

What does a full Dart scenario suite look like?
mockApi.install(route) builds one fresh http.Client per test and clears the call log, so a scripted response can never leak into the next test. The 429, 500 and 502 retry tests in this suite really wait out the backoff, the same way the Node.js and Go mock-testing guides do, rather than faking the clock; that is why the suite below takes about thirty seconds instead of milliseconds, a reasonable trade-off for a suite that is not run on every keystroke.
sellermagnet_test.dart - the scenario suite, run for real below
// sellermagnet_test.dart - the scenario suite, run for real below.
import 'package:test/test.dart';
import '../mock_api.dart' as mockApi;
import '../retry.dart';
import '../sellermagnet.dart';
const asin = 'B0CL61F39H';
const marketplaceId = 'ATVPDKIKX0DER';
Map<String, dynamic> product({Object? price = 444.99}) => {
'productInfo': {
'asin': asin,
'title': 'PlayStation5 console (slim)',
'buyBoxInfo': {'price': price, 'currencyCode': 'USD'},
'bestsellerRanks': {'main_category': {'name': 'Video Games', 'rank': 31}},
'link': 'https://www.amazon.com/dp/$asin',
},
};
void main() {
test('happy path parses the real response shape', () async {
final client = mockApi.install((ep, p) => mockApi.ok(product()));
final out = await lookup(client, asin, marketplaceId);
expect(out.asin, asin);
expect(out.title, 'PlayStation5 console (slim)');
expect(out.price, 444.99);
expect(out.currency, 'USD');
expect(out.rank, 31);
expect(out.url, 'https://www.amazon.com/dp/$asin');
expect(mockApi.calls.length, 1);
});
test('no featured offer price ("N/A") is not a number', () async {
final client = mockApi.install((ep, p) => mockApi.ok(product(price: 'N/A')));
final out = await lookup(client, asin, marketplaceId);
expect(out.price, isNull);
});
test('404 product not found is billed and must not be retried', () async {
final client = mockApi.install((ep, p) => mockApi.err(404, 'Product not found.'));
await expectLater(
() => getWithRetry(client, 'amazon-product-lookup', {'asin': asin, 'marketplaceId': marketplaceId}),
throwsA(isA<ApiError>().having((e) => e.status, 'status', 404)),
);
expect(mockApi.calls.length, 1, reason: '404 is a real answer; retrying it only pays for it twice');
});
test('free gate 400 missing marketplaceId is not retried', () async {
final client = mockApi.install((ep, p) => mockApi.err(400, 'Missing required parameter(s): marketplaceId'));
await expectLater(
() => getWithRetry(client, 'amazon-product-lookup', {'asin': asin}),
throwsA(isA<ApiError>()
.having((e) => e.status, 'status', 400)
.having((e) => e.message, 'message', contains('marketplaceId'))),
);
expect(mockApi.calls.length, 1);
});
test('401 insufficient credits stops without a retry', () async {
final client = mockApi.install((ep, p) => mockApi.err(401, 'Insufficient user credits.'));
await expectLater(
() => getWithRetry(client, 'amazon-product-lookup', {'asin': asin, 'marketplaceId': marketplaceId}),
throwsA(isA<ApiError>().having((e) => e.status, 'status', 401)),
);
expect(mockApi.calls.length, 1);
});
test('429 concurrency cap is free and retried', () async {
var n = 0;
final client = mockApi.install((ep, p) {
n += 1;
if (n == 1) {
return mockApi.err(429, 'Max N concurrent requests per API key. Retry shortly.', {'retry-after': '1'});
}
return mockApi.ok(product());
});
final data = await getWithRetry(client, 'amazon-product-lookup', {'asin': asin, 'marketplaceId': marketplaceId});
expect(data['productInfo']['asin'], asin);
expect(mockApi.calls.length, 2);
});
test('500 is refunded and retried exactly once', () async {
var n = 0;
final client = mockApi.install((ep, p) {
n += 1;
return mockApi.err(500, 'internal error');
});
await expectLater(
() => getWithRetry(client, 'amazon-product-lookup', {'asin': asin, 'marketplaceId': marketplaceId}),
throwsA(isA<ApiError>().having((e) => e.status, 'status', 500)),
);
expect(mockApi.calls.length, 2, reason: 'one retry after the first 500, then stop');
});
test('502 is billed and retried up to the attempt cap', () async {
final client = mockApi.install((ep, p) => mockApi.err(502, 'upstream error'));
await expectLater(
() => getWithRetry(client, 'amazon-product-lookup', {'asin': asin, 'marketplaceId': marketplaceId}),
throwsA(isA<ApiError>().having((e) => e.status, 'status', 502)),
);
expect(mockApi.calls.length, 4, reason: 'default attempt cap is 4, each attempt billed');
});
test('an html error page does not parse as a success body', () async {
final client = mockApi.install((ep, p) => const mockApi.RouteResponse.html(503, '<html>upstream error</html>'));
await expectLater(
() => getWithRetry(client, 'amazon-product-lookup', {'asin': asin, 'marketplaceId': marketplaceId}),
throwsA(isA<ApiError>().having((e) => e.status, 'status', 503)),
);
});
test('mock fails closed without install', () async {
final client = mockApi.blocked();
await expectLater(
() => get(client, 'amazon-product-lookup', {'asin': asin, 'marketplaceId': marketplaceId}),
throwsStateError,
);
});
}
dart test (unmodified run)
Loading test/sellermagnet_test.dart
test/sellermagnet_test.dart: happy path parses the real response shape
test/sellermagnet_test.dart: no featured offer price ("N/A") is not a number
test/sellermagnet_test.dart: 404 product not found is billed and must not be retried
test/sellermagnet_test.dart: free gate 400 missing marketplaceId is not retried
test/sellermagnet_test.dart: 401 insufficient credits stops without a retry
test/sellermagnet_test.dart: 429 concurrency cap is free and retried
test/sellermagnet_test.dart: 500 is refunded and retried exactly once
test/sellermagnet_test.dart: 502 is billed and retried up to the attempt cap
test/sellermagnet_test.dart: an html error page does not parse as a success body
test/sellermagnet_test.dart: mock fails closed without install
+10: All tests passed!
Never hand-write a mock of sellermagnet.dart itself
A mock that reimplements lookup() or getWithRetry() tests the mock's own logic, not the real client. Fake http.Client, one level below your code, so a real bug in the parsing or retry logic still shows up as a failing test.
Does the same pattern work for other Dart HTTP clients?
Yes - fake the one object the real code calls to reach the network, whatever that object is. A project built on dio instead of package:http replaces dio's own adapter the same way this guide replaces http.Client; the principle is the same one the C#, Java and Go mock-testing guides use for HttpMessageHandler, OkHttpClient and RoundTripper. The 429/Retry-After guide and the 502/503 retry guide are the production behaviour this test suite is checking against; keep all three in sync when the retry logic changes. Credit costs and the free trial are on the pricing page, and every endpoint's parameters are in the API documentation and code examples.
Frequently Asked Questions
Can my Dart tests call the real SellerMagnet API instead of faking it?
They can, but every call is billed the same as production traffic, so a CI run that fires on every push spends credits on every build, and a flaky network turns a code bug into a failed pipeline. Faking only the http.Client keeps the real sellermagnet.dart / retry.dart under test while the API itself never sees a request.
Why fake http.Client instead of writing my own lookup() stub?
package:http already ships MockClient in http/testing.dart, one function below your own code that intercepts the exact http.Client.get() call sellermagnet.dart makes. A hand-written stub of lookup() itself would test the stub's logic, not the parsing and retry code that ships.
How do I avoid real waits for a 429, 500 or 502 retry test?
This suite does not shorten the backoff: retry.dart's real exponential wait runs for real, so a passing 429/500/502 test is proof the real wait and the real Retry-After handling work, not just that the code path was reached. The 502 test alone waits out three real backoffs, which is why the whole suite takes about half a minute instead of milliseconds.
Should the fake client allow a request through if a test forgets to call install()?
No. Build the default client with blocked(), a MockClient whose handler always throws a StateError, and have every test build its own client from install(route) instead. A forgotten install then fails the test loudly instead of quietly sending a real, billed request.
Does the fake also verify the api_key travels correctly?
Yes. install()'s handler reads request.url.queryParameters and throws if api_key is missing, the same transport the Dart quickstart uses, so a code change that drops the parameter fails every single test instead of only showing up as a live 401.
Bottom line: fake http.Client (or your language's equivalent one layer below the HTTP call), run the real client code against scripted responses for every billed, free and refunded status, and make the fake fail closed so a forgotten setup cannot send a real, billed request. The suite above runs on package:http and package:test alone and spends zero credits.