An async test must remain alive until the behavior it verifies completes. Return or await the future and use a fake dependency for ordinary logic tests. Calling a public API on every test run makes network availability part of your test suite.
Define a small injectable behavior
Future<String> invoiceLabel(Future<int> Function() loadCount) async {
final count = await loadCount();
return '$count invoices';
}
After importing this function and package:test in your own test file, these test bodies verify success and failure:
test('formats the returned count', () async {
final label = await invoiceLabel(() async => 3);
expect(label, '3 invoices');
});
test('preserves an upstream failure', () async {
await expectLater(
invoiceLabel(() async => throw StateError('Offline')),
throwsStateError,
);
});
These are fragments inside an ordinary void main() test entry point. The fake supplies one known result without creating a socket or waiting for an arbitrary delay.
Cover lifecycle behavior separately
For a stream consumer, use a controlled stream to verify data, error, completion and cancellation. Close owned controllers in teardown. For a clock-dependent operation, pass a clock function or use suitable fake-time tooling instead of sleeping for seconds.
Race-sensitive code needs a deliberate synchronization point. A test that waits a fixed delay can pass on one laptop and fail on a busy build server. Use a completer or controlled dependency to decide exactly when a result becomes available.
Exercise
Add a test where the count future completes only after a completer is triggered. Verify the operation has not produced a label before that point. Then test a retry policy with a fake recording the number of calls, without making a real remote request.