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.
Dart uses Future objects to represent asynchronous operations.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With