使用Dart嘲笑HTTP响应 [英] Mocking HTTP response with Dart
问题描述
我一直在开发一个新的API包装器,不想在每次运行单元测试时调用API。因此,如这里所述,我嘲笑它。
I have been working on a new API wrapper and don't want to be calling the API every time my unit tests run. So as described here, I'm mocking it.
我最初认为我嘲笑它的方式有问题,但似乎问题出在其他地方。
I initially thought there was something wrong with the way I'm mocking it, but it seems the problem is elsewhere.
我想要完成的事很简单。当我的单元测试运行时,我想返回一个值,好像我已经从外部API中获取信息,我正在整合。
What I'm trying to accomplish is very simple. When my unit test run, I would like to return a value as if I had gone out to get the information from the external API I'm integrating with.
我初始化我的类用http.Client作为可选参数,所以我可以传递它在单元测试运行时这样:
I initialise my class with http.Client as an optional parameter, so I can pass it in when the unit tests run as such:
SampleClass(String arg1, String arg2, [http.Client httpClient = null]) {
this._arg1 = arg1;
this._arg2 = arg2;
_httpClient = (httpClient == null) ? http.Request : httpClient;
}
Future apiRequest(String resource, [Map<String, String> body]) {
var url = buildBaseUrl(resource).toString();
var request = new http.Request('POST', Uri.parse(url));
request.bodyFields = body;
return this._httpClient.send(request).then((response) => response.stream.bytesToString().then((value) => value.toString()));
}
在我的单元测试中,我创建了以下mock类:
In my unit test I have created the following mock class:
class HttpClientMock extends Mock implements http.Client {
noSuchMethod(i) => super.noSuchMethod(i);
}
class HttpResponseMock extends Mock implements http.Response {
noSuchMethod(i) => super.noSuchMethod(i);
}
在我的单元测试检查响应我做以下:
And in my unit test to check the response I'm doing the following:
test("Send SMS errors with wrong account", () {
var mockHttpClient = new HttpClientMock()
..when(callsTo('send')).alwaysReturn(message401);
var sample = new SampleClass(_arg1, _arg2, mockHttpClient);
future = sample.apiRequest(...parameters here...).then((value) => value.toString());
expect(future.then((value) => JSON.decode(value)), completion(equals(JSON.decode(message401))));
});
所以,你可以看到,我试图让它调用send返回 message401
,这只是一个 JSON
字符串。
So, as you can see, I am trying to make it so calling send returns message401
, which is just a JSON
string.
,因为 message401
是一个字符串,并且因为我的代码试图使用它作为一个未来,我总是得到错误:
This is not happening, since message401
is a string, and because my code tries to use it as a Future, I always get the error:
顶级未捕获错误:类'String'没有实例方法
'then'。
Top-level uncaught error: Class 'String' has no instance method 'then'.
我完全明白为什么我得到这个错误,但不知道如何解决。
I totally understand why I'm getting this error, but have no idea about how to go around it.
任何帮助。
Any help appreciated.
推荐答案
http
包有测试库与 MockClient 。
这篇关于使用Dart嘲笑HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!