How to mock server response - client on server side

二次信任 提交于 2019-12-21 17:29:04

问题


I'm trying dart and I'm writing a client on the server side :

new HttpClient().post(InternetAddress.LOOPBACK_IP_V4.host, 7474, '/path').then((HttpClientRequest request) {
request.headers.contentType = ContentType.JSON;
request.headers.add(HttpHeaders.ACCEPT, ContentType.JSON);
request.write(JSON.encode(jsonData));

return request.close();
}).then((HttpClientResponse response) {
response.transform(UTF8.decoder).listen((contents) {
  _logger(contents);
  // stuff
});
});

and I would like to mock the server response.

What is the best solution ?

  • Create a server in my test class that will return the value I expect ?
  • or mock the HttpClientResponse ?

Thanks for your help ! (code would be greatly appreciated ;D)


回答1:


The http packages provides support for this.

See http://www.dartdocs.org/documentation/http/0.11.1+1/index.html#http/http-testing for examples.

import 'dart:convert';
import 'package:http/testing.dart';

var client = new MockClient((request) {
  if (request.url.path != "/data.json") {
    return new Response("", 404);
  }
  return new Response(JSON.encode({
    'numbers': [1, 4, 15, 19, 214]
  }, 200, headers: {
    'content-type': 'application/json'
  });
};


来源:https://stackoverflow.com/questions/25703029/how-to-mock-server-response-client-on-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!