Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have found several solutions. One solution is to pack the method into a try-catch block:

test('simple call wiht try catch', () async {
  try {
    await impl.throwExceptionAfter(1);
  } catch (e) {
    expect(e, isInstanceOf<Exception>()); 
  }

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

The other solution is to put the check on in the method whenComplete:

test('simple call with whenComplete', () async {
  expect(
    impl.throwExceptionAfter(1).whenComplete(() {
      var count = impl.count();
      expect(count, 1);
    }),
    throwsException);
});

I hope the answer helps others.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...