Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for an asynchronous setup in a unit test, in Dart?

My unit tests require a setup that needs to run asynchronously. That is, I need to wait for the setup to finish before the tests are run, but the setup deals with Futures.

like image 266
Seth Ladd Avatar asked Feb 21 '13 04:02

Seth Ladd


People also ask

Is Dart synchronous or asynchronous?

Dart uses Future objects to represent asynchronous operations.

How do you test asynchronous?

To test asynchronous code, we use the XCTestExpectation class and wait for the expected outcome. The workflow is to create an expectation, and then when the asynchronous task completes successfully, we fulfil that expectation. We will wait for a specific amount of time for the expectation to be fulfilled.

How do you use async await in Flutter?

We put await in front of an asynchronous function to make the subsequence lines waiting for that future's result. We put async before the function body to mark that the function support await . An async function will automatically wrap the return value in Future if it doesn't already.

What does await do in Dart?

When you await an asynchronous function, the execution of the code within the caller suspends while the async operation is executed. When the operation is completed, the value of what was awaited is contained within a Future object.


2 Answers

While the accepted answer by Seth is correct, the following example may be easier to understand and reuse. It returns a Future and performs the setup in the Future's async worker function:

setUp(() {
  return Future(() async {
    await someFuture();
    callSomeFunction();
    await anotherFuture();
  });
});

The test cases will be called after the last call to anotherFuture() returns.

like image 136
Ber Avatar answered Oct 06 '22 10:10

Ber


With Dart M3, the setUp function can optionally return a Future. If setUp returns a Future, the unittest framework will wait for the Future to complete before running the individual test methods.

Here is an example:

group(('database') {
  var db = createDb();
  setUp(() {
    return openDatabase()
      .then((db) => populateForTests(db));
  });

  test('read', () {
    Future future = db.read('foo');
    future.then((value) {
      expect(value, 'bar');
    });
    expect(future, completes);
  });
});

Learn more about setUp.

like image 31
Seth Ladd Avatar answered Oct 06 '22 10:10

Seth Ladd