我的单元测试需要一个需要异步运行的设置。也就是说,我需要在运行测试之前等待设置完成,但设置处理的是 Futures。
问问题
1723 次
2 回答
14
使用 Dart M3,该setUp
函数可以选择返回一个Future
. 如果 setUp 返回一个 Future,unittest 框架将在运行各个测试方法之前等待 Future 完成。
这是一个例子:
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);
});
});
了解有关设置的更多信息。
于 2013-02-21T04:24:02.983 回答
4
虽然 Seth 接受的答案是正确的,但以下示例可能更易于理解和重用。它返回 aFuture
并在 Future 的异步工作函数中执行设置:
setUp(() {
return Future(() async {
await someFuture();
callSomeFunction();
await anotherFuture();
});
});
测试用例将在最后一次调用anotherFuture()
返回后被调用。
于 2020-12-21T12:22:55.427 回答