Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
测试Dart API包装器_Dart - Fatal编程技术网

测试Dart API包装器

测试Dart API包装器,dart,Dart,我目前正在为wit.ai编写一个API包装器。我想向这个包装器添加测试,但我不确定如何添加测试,因为我正在使用http库发送http请求 代码如下所示: Future message(String q) { Map<String, String> headers = { 'Accept': 'application/vnd.wit.${apiVersion}+json', 'Authorization': 'Bearer ${token}' }

我目前正在为wit.ai编写一个API包装器。我想向这个包装器添加测试,但我不确定如何添加测试,因为我正在使用
http
库发送http请求

代码如下所示:

Future message(String q) {
    Map<String, String> headers = {
      'Accept': 'application/vnd.wit.${apiVersion}+json',
      'Authorization': 'Bearer ${token}'
    };
    return http
        .get('https://api.wit.ai/message?q=${q}', headers: headers)
        .then((response) {
      return JSON.decode(response.body);
    }).catchError((e, stackTrace) {
      return JSON.decode(e);
    });
  }
未来消息(字符串q){
映射头={
'Accept':'application/vnd.wit.${apiVersion}+json',
'Authorization':'Bearer${token}'
};
返回http
.get('https://api.wit.ai/message?q=${q}',头:头)
.然后((回应){
返回JSON.decode(response.body);
}).catchError((e,stackTrace){
返回JSON.decode(e);
});
}

有了这段代码,我如何编写一个实际上不发送HTTP请求的测试呢?

这通常是通过依赖项注入来解决的。您的API包装器类可以有如下构造函数:

class MyWrapper {
  final http.BaseClient _httpClient;
  MyWrapper({BaseClient httpClient: new http.Client()})
      : _httpClient = httpClient;

  // ...
}
使用带有默认值的命名参数意味着普通用户无需担心创建默认值

在您的方法中,您使用
客户端
,而不是使用
http
库的静态方法:

Future message(String q) {
  Map<String, String> headers = {
    'Accept': 'application/vnd.wit.${apiVersion}+json',
    'Authorization': 'Bearer ${token}'
  };
  return _httpClient
      .get('https://api.wit.ai/message?q=${q}', headers: headers)
      .then((response) {
    return JSON.decode(response.body);
  }).catchError((e, stackTrace) {
    return JSON.decode(e);
  });
}
无需运行本地服务器,而且速度更快

var wrapper = new MyWrapper(httpClient: myMockClient);