【问题标题】:How to mock HttpClientResponse to return a String如何模拟 HttpClientResponse 以返回字符串
【发布时间】:2018-09-13 11:46:24
【问题描述】:

我正在尝试在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,但这也返回了一个空值。

提前非常感谢!

【问题讨论】:

    标签: dart flutter flutter-test


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2019-05-27
    • 2019-12-06
    相关资源
    最近更新 更多