jeudi 7 janvier 2021

Testing side effects in an async function that throw exception in Dart

I want to test an async function for its exception behavior and side effects.

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();
  }
}

The test:

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

The first test 'simple call with waiting' works, but in this test i wait a certain time to make sure that the method is completed. the second test does not work because first the test of the count is checked before the method is completed.

Is there a way to wait for the expect like that:

test('simple call', () async {
  await expect(impl.throwExceptionAfter(1), throwsException);

  var count = impl.count();
  expect(count, 1);
});

I have already tried several possibilities but could not find a solution so far. The documentation has not helped me either. Asynchronous Tests

My tests can be found here: Github

Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire