使用Dart模拟HTTP响应

Mar*_*ona 3 mocking dart dart-unittest dart-mock

我一直在研究新的API包装器,并且不希望每次运行单元测试时都调用API.因此,作为描述在这里,我嘲笑它.

我最初认为我嘲笑它的方式有问题,但似乎问题出在其他地方.

我想要完成的事情非常简单.当我的单元测试运行时,我想返回一个值,好像我已经出去从我正在集成的外部API获取信息.

我使用http.Client作为可选参数初始化我的类,所以我可以在单元测试运行时将其传入:

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()));
}
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中,我创建了以下模拟类:

class HttpClientMock extends Mock implements http.Client {
  noSuchMethod(i) => super.noSuchMethod(i);
}

class HttpResponseMock extends Mock implements http.Response {
    noSuchMethod(i) => super.noSuchMethod(i);
}
Run Code Online (Sandbox Code Playgroud)

在我的单元测试中检查响应我正在做以下事情:

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))));
});
Run Code Online (Sandbox Code Playgroud)

所以,正如你所看到的,我试图让它调用send返回message401,这只是一个JSON字符串.

这不会发生,因为它message401是一个字符串,因为我的代码试图将它用作Future,我总是得到错误:

顶级未捕获错误:类'String'没有实例方法'then'.

我完全理解为什么我会收到这个错误,但不知道如何绕过它.

任何帮助赞赏.

Sea*_*gan 9

http软件包有一个测试库,其中已经为您实现了MockClient.

  • 你们能用MockClient发布一个例子吗 (2认同)