Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkgs/http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
50 changes: 50 additions & 0 deletions pkgs/http/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> 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

Expand Down
Loading