测试Dart API包装器

Sgo*_*kes 3 dart

我目前正在为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);
    });
  }
Run Code Online (Sandbox Code Playgroud)

鉴于此代码,我将如何编写一个实际上不发送HTTP请求的测试?

fil*_*iph 5

传统上这通过依赖注入来解决.您的API包装类可以有一个构造函数,如:

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

  // ...
}
Run Code Online (Sandbox Code Playgroud)

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

在您的方法中,您使用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);
  });
}
Run Code Online (Sandbox Code Playgroud)

但请记住,客户需要关闭.如果你close的API包装器上没有方法,你可能想要a)添加它,或者b)将依赖注入放在message()方法而不是构造函数上.

测试时,设置一个MockClient.像这样传递:

var wrapper = new MyWrapper(httpClient: myMockClient);
Run Code Online (Sandbox Code Playgroud)

无需运行本地服务器,而且速度更快.