我正在尝试在 https://flutter.io/networking/ 之后重构为 dart:io.HttpClient 后编写测试
一切似乎都运行良好,直到
var responseBody = await response.transform(utf8.decoder).join();
以下测试抛出 NoSuchMethodError:方法 'join' 在 null 上被调用。
MockHttpClient http = new MockHttpClient();
MockHttpClientRequest request = new MockHttpClientRequest();
MockHttpHeaders headers = new MockHttpHeaders();
MockHttpClientResponse response = new MockHttpClientResponse();
MockStream stream = new MockStream();
when(http.getUrl(Uri.parse('http://www.example.com/')))
.thenReturn(new Future.value(request));
when(request.headers)
.thenReturn(headers);
when(request.close())
.thenReturn(new Future.value(response));
when(response.transform(utf8.decoder))
.thenReturn(stream);
when(stream.join())
.thenReturn(new Future.value('{"error": {"message": "Some error"}}'));
我确实看到了 How to mock server response - client on server side ,但它使用的是 http 包,而不是 dart:io。
我也试过 https://github.com/flutter/flutter/blob/master/dev/manual_tests/test/mock_image_http.dart 但它也返回一个空值。
非常感谢!
最佳答案
问题在于,当您模拟流时,您实际上需要实现大量不同的方法才能使其正常工作。如果您喜欢 flutter repo 中的示例,最好使用真正的 Stream。为确保您的 body 设置正确,请使用 utf8 编码器。
final MockHttpClientResponse response = new MockHttpClientResponse();
// encode the response body as bytes.
final List<int> body = utf8.encode('{"foo":2}');
when(response.listen(typed(any))).thenAnswer((Invocation invocation) {
final void Function(List<int>) onData = invocation.positionalArguments[0];
final void Function() onDone = invocation.namedArguments[#onDone];
final void Function(Object, [StackTrace]) onError = invocation.namedArguments[#onError];
final bool cancelOnError = invocation.namedArguments[#cancelOnError];
return new Stream<List<int>>.fromIterable(<List<int>>[body]).listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError);
});
关于dart - 如何模拟 HttpClientResponse 以返回字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49642113/