useMockClient function
void
useMockClient({})
Configure all RestAPI instances to use an in-memory mock client.
Built on the public setClientFactory seam, so nothing in the core library references test scaffolding.
Call in test setup:
setUp(() => useMockClient()); // 200 + fake data
setUp(() => useMockClient(shouldFail: true, failStatusCode: 500));
Also usable for running the app against mock data in development:
// bootstrap.dart — Environment.useMocks is a compile-time constant, so
// this branch is tree-shaken out of release builds entirely.
if (Environment.useMocks) useMockClient();
By default every request resolves to FakeUtils.fakeJson, which is generic
and fine for exercising status handling. Supply responseFactory to return
app-shaped data keyed off the request:
useMockClient(responseFactory: (request) => switch (request.url.path) {
'/api/v1/products' => [ProductFake.fake().toJson(), ProductFake.fake().toJson()],
_ => ProductFake.fake().toJson(),
});
Implementation
void useMockClient({
bool shouldFail = false,
int failStatusCode = 400,
Object? Function(http.Request request)? responseFactory,
}) {
setClientFactory(
() => MockClient((request) async {
if (shouldFail) {
return http.Response(
jsonEncode({'error': 'Mock failure', 'path': request.url.path}),
failStatusCode,
);
}
final body = responseFactory?.call(request) ?? FakeUtils.fakeJson();
return http.Response(jsonEncode(body), 200);
}),
);
}