【发布时间】:2019-10-15 18:59:28
【问题描述】:
在我的代码中,函数在一分钟后向流发出值。假设它是一个计时器。我想做单元测试(不是小部件测试,因为该函数位于 bloc 文件中)。我尝试按照文档https://api.flutter.dev/flutter/quiver.testing.async/FakeAsync-class.html 中的描述使用 fakeAsync,但没有运气。超时测试失败。 测试代码:
class BarcodeBloc {
Timer _timer;
StreamController<bool> _timerFinished;
BarcodeBloc() {
_timerFinished = new StreamController();
}
Stream<bool> get cameraTimeout => _timerFinished.stream;
void _tick() {
_timerFinished.add(true);
}
void startTimer() {
stopTimer();
print("starting timer");
_timer = Timer(interval, _tick);
}
void stopTimer() {
if (_timer != null) {
_timer.cancel();
}
}
}
我的测试代码:
void main() {
test("After one minute emits true", () {
new FakeAsync().run((async) {
BarcodeBloc barcodeBloc = new BarcodeBloc(preferenceProvider);
barcodeBloc.startTimer();
async.elapse(duration);
expect(barcodeBloc.cameraTimeout, emits(true));
});
}
【问题讨论】:
-
不确定你是否仍然有这个问题,但我正在做一些非常类似的事情,使用 async.elapse 在由于使用
debounce()而有时间延迟的流上快进时间并且在标准单元测试(not 小部件测试)中使用当前的 strable v1.12.13+hotfix.7)按预期工作。
标签: unit-testing flutter