diff --git a/pkgs/http/CHANGELOG.md b/pkgs/http/CHANGELOG.md index 6d84d9c080..99a5b5c448 100644 --- a/pkgs/http/CHANGELOG.md +++ b/pkgs/http/CHANGELOG.md @@ -4,6 +4,7 @@ parameter is only added for text and XML media types. This brings the behavior of `package:http` in line with RFC-8259. * Export `MediaType` from `package:http_parser`. +* Added a section on testing to `README.md`. ## 1.5.0 diff --git a/pkgs/http/README.md b/pkgs/http/README.md index 547cb64e1f..b3080c0551 100644 --- a/pkgs/http/README.md +++ b/pkgs/http/README.md @@ -82,6 +82,56 @@ class UserAgentClient extends http.BaseClient { } } ``` +## Testing + +For better testability, especially in Flutter applications, it's recommended +to use a [Client][] instance rather than the top-level functions like +`http.get()` or `http.post()`. This approach makes it easier to mock HTTP +requests in your tests. + +```dart +// Instead of using static methods (harder to test): +// var response = await http.get(Uri.https('example.com', 'data.json')); + +// Use a Client instance (easier to test): +class DataService { + final http.Client client; + + DataService({http.Client? client}) : client = client ?? http.Client(); + + Future fetchData() async { + var response = await client.get(Uri.https('example.com', 'data.json')); + return response.body; + } +} +``` + +In your tests, you can easily mock the HTTP client: + +```dart +import 'package:http/testing.dart'; +import 'package:test/test.dart'; + +void main() { + test('fetchData returns expected data', () async { + final mockClient = MockClient((request) async { + return http.Response('{"key": "value"}', 200); + }); + + final dataService = DataService(client: mockClient); + final result = await dataService.fetchData(); + + expect(result, '{"key": "value"}'); + }); +} +``` + +> [!TIP] +> You can also use `package:mockito` to mock `http.Client`. +> For more detailed guidance, see the +> [Flutter testing cookbook](https://docs.flutter.dev/cookbook/testing/unit/mocking), +> which demonstrates best practices for mocking HTTP requests. + ## Retrying requests