How can I test a method using Future in Dart?

I would like to test a method that POSTs on another server:

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);
  });
}

      

The problem I am having is that my test method ends before the future returned by "_client.post" is executed.

My testing method:

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

      

Thank you for your help!

+3


source to share


1 answer


Your method executePost()

doesn't even return the future, it returns null

.
client.post()

returns the future, but this return value is not used.

Try changing it to:



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);
  });
}

      

+3


source







All Articles