gpt4 book ai didi

dart - Dart单元测试包中的protectAsyncN如何工作?

转载 作者:行者123 更新时间:2023-12-03 03:06:46 28 4
gpt4 key购买 nike

我真的不明白protectAsyncN方法的目的。

有人可以告诉我它应该如何工作吗?例如,假设以下测试用例:

import "package:unittest/unittest.dart";
import "dart:async";

void main() {
test("Protect async", () {
// given
var controller = new StreamController();

// when
controller.add("This is correct!");

// then
controller.stream.listen(protectAsync1((event) {
expect(event, equals("This is correct!"));
}));
});
}

行为应该是什么?我希望此测试用例能够通过,但是会收到以下消息:

unittest-suite-wait-for-done
ERROR: Protect async
Callback called (1) after test case Protect async has already been marked as pass.

0 PASSED, 0 FAILED, 1 ERRORS
Unhandled exception:
Exception: Some tests failed.
#0 SimpleConfiguration.onDone (package:unittest/src/simple_configuration.dart:213:9)
#1 _completeTests (package:unittest/unittest.dart:779:17)
#2 _runTest (package:unittest/unittest.dart:734:19)
#3 _nextTestCase (package:unittest/unittest.dart:641:11)
#4 _asyncRunCallback (dart:async/schedule_microtask.dart:18)
#5 _asyncRunCallback (dart:async/schedule_microtask.dart:21)
#6 _createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:11)
#7 _Timer._createTimerHandler._handleTimeout (timer_impl.dart:151)
#8 _Timer._createTimerHandler._handleTimeout (timer_impl.dart:159)
#9 _Timer._createTimerHandler._handleTimeout (timer_impl.dart:159)
#10 _Timer._createTimerHandler.<anonymous closure> (timer_impl.dart:166)
#11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:93)

我试过使用guardAsync,它按预期工作。但是,我真的不明白protectAsync。

有人可以解释一下我的目的和正确用法吗?非常感谢!

最佳答案

these docs中被描述为

Wraps the callback in a new function and returns that function. The new function will be able to handle exceptions by directing them to the correct test. This is thus similar to expectAsync0. Use it to wrap any callbacks that might optionally be called but may never be called during the test. callback should take 0 positional arguments (named arguments are not supported). id can be used to identify the callback in error messages (for example if it is called after the test case is complete).



因此,大概这可以使测试框架更好地处理异步测试(您不希望您的测试立即完成,然后您启动的一些异步工作会引发异常,但不会因为测试已经失败而使测试失败完成)。

我不确定为什么测试会失败。这表明可能有问题:/

关于dart - Dart单元测试包中的protectAsyncN如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19958625/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com