如何模拟HttpClientResponse返回一个String

时间:2018-04-04 03:09:47

标签: dart flutter flutter-test

我试图在重构之后编写一个测试:io.HttpClient跟https://flutter.io/networking/

之前,一切似乎都运转良好
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,但也返回了空。

提前多多谢谢!

1 个答案:

答案 0 :(得分:2)

问题在于,当您模拟流时,实际上需要实现大量不同的方法才能使其正常工作。如果你喜欢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);
});