How to use `expectAsync2` correctly when writing dart unittest?

半城伤御伤魂 提交于 2019-12-02 03:00:56

问题


I was trying this method expectAsync2, so there was this question: Why the async test passed, but there are some error messages displayed?

But it seems I didn't use it correctly. Is there any good example of expectAsync2?


回答1:


In the referenced question expectAsync was just used to guard a async call so that the test doesn't end before the call of new Timer(...) finishes.

You can additionally add provide how often (min/max) the method has to be called to satisfy the test. If your tested functionality calls a method with more than one parameter you use `expectAsync2)

The mistake in your referenced question was, that your call to expectAsyncX was delayed too. The call to expectAsyncX has to be made before the async functionality is invoked to register which method has to be called.

library x;

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

class SubjectUnderTest {
  int i = 0;
  doSomething(x, y) {
    i++;
    print('$x, $y');
  }
}

void main(List<String> args) {

  test('async test, check a function with 2 parameters', () {
    var sut = new SubjectUnderTest();
    var fun = expectAsync2(sut.doSomething, count: 2, max: 2, id: 'check doSomething');

    new Timer(new Duration(milliseconds:200), () {
        fun(1,2);
        expect(sut.i, greaterThan(0));
    });

    new Timer(new Duration(milliseconds:100), () {
        fun(3,4);
        expect(sut.i, greaterThan(0));
    });

  });
}

You can check what happens if you set count and max to 3.




回答2:


You can have a look at the Asynchronous tests section of the article Unit Testing with Dart.



来源:https://stackoverflow.com/questions/21460073/how-to-use-expectasync2-correctly-when-writing-dart-unittest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!