How to test a method using a Future in Dart?

Issue

I would like to test a method which execute a POST 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’m dealing with is that my testing 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);
  }
});

Thanks for your help !

Solution

Your executePost() method doesn’t even return a future, it returns null.
client.post() returns a future but this return value isn’t used.

Try to change 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);
  });
}

Answered By – Günter Zöchbauer

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *