@@ -82,6 +82,56 @@ class UserAgentClient extends http.BaseClient {
8282 }
8383}
8484```
85+ ## Testing
86+
87+ For better testability, especially in Flutter applications, it's recommended
88+ to use a [ Client] [ ] instance rather than the top-level functions like
89+ ` http.get() ` or ` http.post() ` . This approach makes it easier to mock HTTP
90+ requests in your tests.
91+
92+ ``` dart
93+ // Instead of using static methods (harder to test):
94+ // var response = await http.get(Uri.https('example.com', 'data.json'));
95+
96+ // Use a Client instance (easier to test):
97+ class DataService {
98+ final http.Client client;
99+
100+ DataService({http.Client? client}) : client = client ?? http.Client();
101+
102+ Future<String> fetchData() async {
103+ var response = await client.get(Uri.https('example.com', 'data.json'));
104+ return response.body;
105+ }
106+ }
107+ ```
108+
109+ In your tests, you can easily mock the HTTP client:
110+
111+ ``` dart
112+ import 'package:http/testing.dart';
113+ import 'package:test/test.dart';
114+
115+ void main() {
116+ test('fetchData returns expected data', () async {
117+ final mockClient = MockClient((request) async {
118+ return http.Response('{"key": "value"}', 200);
119+ });
120+
121+ final dataService = DataService(client: mockClient);
122+ final result = await dataService.fetchData();
123+
124+ expect(result, '{"key": "value"}');
125+ });
126+ }
127+ ```
128+
129+ > [ !TIP]
130+ > You can also use ` package:mockito ` to mock ` http.Client ` .
131+ > For more detailed guidance, see the
132+ > [ Flutter testing cookbook] ( https://docs.flutter.dev/cookbook/testing/unit/mocking ) ,
133+ > which demonstrates best practices for mocking HTTP requests.
134+
85135
86136## Retrying requests
87137
0 commit comments