How to test a method using a Future in Dart?


I would like to test a method which execute a POST on another server :

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

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

The problem I’m dealing with is that my testing method ends before the future returned by “” is executed.

My testing method :

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

Thanks for your help !


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

Try to change it to:

Future executePost() {
  return"http://localhost/path", body : '${data}').then((response) {"Response status : ${response.statusCode}");"Response body : ${response.body}");
    return true;
  }).catchError((error, 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 *