如何在Dart中使用Future测试一个方法?

3

我想测试一个在另一台服务器上执行POST请求的方法:

Future executePost() {
  _client.post("http://localhost/path", body : '${data}').then((response) {
    _logger.info("Response status : ${response.statusCode}");
    _logger.info("Response body : ${response.body}");

    Completer completer = new Completer();
    completer.complete(true);
    return completer.future;
  }).catchError((error, stackTrace) {
    _logger.info(error);
    _logger.info(stackTrace);
  });
}

我所面临的问题是,我的测试方法在"_client.post"返回的未来执行之前就结束了。

我的测试方法:

test('should be true', () {
  try {
    Future ok = new MyClient().executePost();
    expect(ok, completion(equals(true)));
  } catch(e, s) {
    _logger.severe(e);
    _logger.severe(s);
  }
});

感谢您的帮助!
1个回答

3

你的executePost()方法甚至没有返回一个future,它返回了null
client.post()返回一个future,但是这个返回值并没有被使用。

尝试修改为:

Future executePost() {
  return _client.post("http://localhost/path", body : '${data}').then((response) {
    _logger.info("Response status : ${response.statusCode}");
    _logger.info("Response body : ${response.body}");
    return true;
  }).catchError((error, stackTrace) {
    _logger.info(error);
    _logger.info(stackTrace);
  });
}

1
谢谢!它有效 :) 还不熟悉 futures :p - matth3o

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接