Home > OS >  How can I wait for a future to finish during a test if it wasn't called from the test directly?
How can I wait for a future to finish during a test if it wasn't called from the test directly?

Time:10-07

I'm trying to write a test for a method that makes a call to an API using Dio. The Dio response has been mocked using http_mock_adapter. My problem is that I need to wait for the API call to finish before continuing with the test, and I can't simply use await since the method I'm testing isn't asynchronous. Is there a way to wait for a future that wasn't called from the test?

Below is an example of what I'm talking about:

String apiResult = 'foo';

void methodToTest(){
  apiCall().then((value) => apiResult = value);
}
test('methodToTest works', () {
  expect(apiResult, equals('foo'));

  methodToTest();

  // I need to wait for apiCall to finish here.

  expect(apiResult, equals('bar'));
});

Previously, I have been able to use Future.delayed(Duration.zero) when I have had situations like this, but it has always seemed like a workaround, and now it doesn't work.

CodePudding user response:

the method I'm testing isn't asynchronous

Congratulations, your tests found a bug.

this is your method after fixing the bug:

Future<void> methodToTest() async {
  apiResult = await apiCall();
}
  • Related