我目前正在为 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);
});
}
鉴于此代码,我将如何编写一个实际上不发送 HTTP 请求的测试?
最佳答案
传统上,这是通过依赖注入(inject)来解决的。您的 API 包装器类可以具有如下构造函数:
class MyWrapper {
final http.BaseClient _httpClient;
MyWrapper({BaseClient httpClient: new http.Client()})
: _httpClient = httpClient;
// ...
}
使用具有默认值的命名参数意味着普通用户无需担心创建 Client .
在您的方法中,您使用 Client
而不是使用 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);
});
}
但请记住,客户端需要关闭。如果您的 API 包装器上没有 close
方法,您可能需要 a) 添加它,或 b) 将依赖项注入(inject)放在 message()
方法上而不是在构造函数上。
测试时,set up a MockClient
。像这样传递:
var wrapper = new MyWrapper(httpClient: myMockClient);
无需运行本地服务器,而且速度更快。
关于dart - 测试 Dart API 包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37485861/