2

I really don't understand the purpose of protectAsyncN methods.

Could someone please explain me how should it work? For example, imagine following test case:

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!"));
    }));
  });
}

What should the behavior be? I would expect this test case to pass, however I get the following message:

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)

I have tried using guardAsync and it works as expected. However, I really don't understand protectAsync.

Could someone explain me the purpose and correct usage of it? Thanks a lot!

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Samuel Hapak
  • 6,950
  • 3
  • 35
  • 58

1 Answers1

0

In these docs it's described as

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).

So presumably this is plumbing to allow the test framework to better handle async tests (you don't want your test to immediately complete, and then some async work you kicked off throws an exception, but doesn't fail your test because it was already complete).

I'm not sure why the test would be failing, however; that suggests something might be wrong :/

Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275