如何模拟服务器响应-服务器端客户端

如何模拟服务器响应-服务器端客户端

问题描述:

我正在尝试dart,并且正在服务器端编写一个客户端:

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 ?


  • 在测试类中创建一个服务器,该服务器将返回我期望的值?

  • 或模拟HttpClientResponse吗?

感谢您的帮助! (代码将不胜感激; D)

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

http包对此提供了支持。

请参见 http://www.dartdocs.org/documentation/http/0.11.1+1/index。 html#http / http-testing 例如。

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