【发布时间】:2021-01-08 20:00:42
【问题描述】:
我想测试一个异步函数的异常行为和副作用。
abstract class Async {
int count();
Future<void> throwExceptionAfter(int sec);
}
class ImplAsync extends Async {
int _count = 0;
@override
int count() => _count;
@override
Future<void> throwExceptionAfter(int sec) async {
await Future.delayed(Duration(seconds: sec));
_count++;
throw Exception();
}
}
测试:
void main() {
Async impl;
setUp(() {
impl = ImplAsync();
});
group('throwExeptionAfter', () {
test('simple call with waiting', () async {
expect(impl.throwExceptionAfter(0), throwsException);
await Future.delayed(Duration(seconds: 1));
var count = impl.count();
expect(count, 1);
});
test('simple call', () async {
expect(impl.throwExceptionAfter(1), throwsException);
var count = impl.count();
expect(count, 1);
});
});
}
第一个测试“带等待的简单调用”有效,但在此测试中,我等待一段时间以确保该方法完成。第二个测试不起作用,因为在方法完成之前首先检查计数的测试。
有没有办法像这样等待期望:
test('simple call', () async {
await expect(impl.throwExceptionAfter(1), throwsException);
var count = impl.count();
expect(count, 1);
});
我已经尝试了几种可能性,但到目前为止找不到解决方案。文档也没有帮助我。 Asynchronous Tests
我的测试可以在这里找到:Github
感谢您的帮助。
【问题讨论】:
标签: unit-testing dart asynchronous testing async-await