测试Dart API包装器
我目前正在为wit.ai编写一个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}' }
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);