Home > Software design >  Why is Future in this test never completing?
Why is Future in this test never completing?

Time:06-23

I was testing a service I wrote which returns a Future, but this weird behavior happened when I awaited the result of the future and the test never completed. Trying to reproduce the error in a minimal way, I got this:

import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('...',
      (WidgetTester tester) async {
    print('awaiting');
    await Future.delayed(Duration(seconds: 2)); // never completes
    print('done'); // not reached
  });
}

but this completes normally:

import 'package:flutter_test/flutter_test.dart';

void main() {
  test('...',
      () async {
    print('awaiting');
    await Future.delayed(Duration(seconds: 2)); // completes normally
    print('done'); // prints "done"
  });
}

why is the first one not completing, what am I missing?

CodePudding user response:

using tester.runAsync solves the problem (I still don't know why I need to run my function within this function). It is used like this as per enter image description here

  • Related