Skip to content

Commit 81b5979

Browse files
docs(http): add http.client Testing section with Flutter testing cookbook recommendation (#1836)
1 parent 5ec2476 commit 81b5979

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

pkgs/http/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
parameter is only added for text and XML media types. This brings the
55
behavior of `package:http` in line with RFC-8259.
66
* Export `MediaType` from `package:http_parser`.
7+
* Added a section on testing to `README.md`.
78

89
## 1.5.0
910

pkgs/http/README.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)