send method
Send the HTTP request and return the response.
Constructs the complete HTTP request with all configured headers, body content, and authentication, then sends it to the server.
Example:
final response = await testApp.get('/api/users')
.header('Accept', 'application/json')
.send();
print('Status: ${response.statusCode}');
print('Body: ${response.body}');
Returns a TestResponse with the server's response. Throws TestException if the request fails due to network issues.
Implementation
Future<TestResponse> send() async {
final uri = Uri.parse('$baseUrl$path');
try {
final request = await _client.openUrl(method, uri);
// Set headers
_headers.forEach((key, value) {
request.headers.add(key, value);
});
// Set content type if specified
if (_contentType != null) {
request.headers.contentType = ContentType.parse(_contentType!);
}
// Write body if present
if (_body != null) {
String bodyString;
if (_body is Map || _body is List) {
if (_contentType == 'application/x-www-form-urlencoded') {
// Form encode
final formData = _body as Map<String, String>;
bodyString = formData.entries
.map((e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
.join('&');
} else {
// JSON encode
bodyString = jsonEncode(_body);
if (_contentType == null) {
request.headers.contentType = ContentType.json;
}
}
} else {
bodyString = _body.toString();
}
request.write(bodyString);
}
final response = await request.close();
final responseBody = await response.transform(utf8.decoder).join();
return TestResponse(response, responseBody);
} catch (e) {
throw TestException('Request failed: $e');
}
}