4

我正在尝试在https://flutter.io/networking/重构为 dart:io.HttpClient 之后编写测试

一切似乎都运行良好,直到

var responseBody = await response.transform(utf8.decoder).join();

以下测试引发 NoSuchMethodError:在 null 上调用了方法“join”。

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"}}'));

我确实看到了如何在服务器端模拟服务器响应 - 客户端,但它使用的是 http 包,而不是 dart:io。

我也试过https://github.com/flutter/flutter/blob/master/dev/manual_tests/test/mock_image_http.dart但这也返回一个空值。

非常感谢提前!

4

1 回答 1

4

问题是,当您模拟流时,您实际上需要实现大量不同的方法才能使其正常工作。如果您喜欢flutter repo中的示例,最好使用真正的Stream。为确保您的身体设置正确,请使用 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);
});
于 2018-04-04T03:34:27.520 回答