You can use async/await
in dart. Which would simplify quite a lot your function :
function(DoSomething x, DoSomething y) async {
final result = await x.doSomethingAsync();
if (result != null) {
y.doSomething();
}
}
This way, the function will not complete until x.doSomething
has completed. You can then test your function using the same async/await
operators with an async test
.
You'd have this :
test('test my function', () async {
await function(x, y);
});
Okey, but how do I test if the functions got called ?
For this, you can use mockito which is a mock package for tests purposes.
Let's assume your x/y class is :
class DoSomething {
Future<Object> doSomethingAsync() async {}
void doSomething() {}
}
you could then use Mockito by mocking your class methods using :
// Mock class
class MockDoSomething extends Mock implements DoSomething {
}
finally you could use that mock inside your test by doing :
test('test my function', () async {
final x = new MockDoSomething();
final y = new MockDoSomething();
// test return != null
when(x.doSomethingAsync()).thenReturn(42);
await function(x, y);
verifyNever(x.doSomething());
verify(x.doSomethingAsync()).called(1);
// y.doSomething must not be called since x.doSomethingAsync returns 42
verify(y.doSomething()).called(1);
verifyNever(y.doSomethingAsync());
// reset mock
clearInteractions(x);
clearInteractions(y);
// test return == null
when(x.doSomethingAsync()).thenReturn(null);
await function(x, y);
verifyNever(x.doSomething());
verify(x.doSomethingAsync()).called(1);
// y must not be called this x.doSomethingAsync returns null here
verifyZeroInteractions(y);
});
function
is not and cannot be async. – Katheryn