问题
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