如果不是直接从测试中调用,我如何等待未来在测试期间完成?
How can I wait for a future to finish during a test if it wasn't called from the test directly?
我正在尝试为使用 Dio. The Dio response has been mocked using http_mock_adapter 调用 API 的方法编写测试。我的问题是我需要等待 API 调用完成才能继续测试,而且我不能简单地使用 await,因为我正在测试的方法不是异步的。有没有办法等待未从测试中调用的未来?
下面是我所说的示例:
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'));
});
以前,当我遇到这种情况时,我可以使用 Future.delayed(Duration.zero)
,但它似乎一直是一种解决方法,但现在它不起作用。
the method I'm testing isn't asynchronous
恭喜,您的测试发现了一个错误。
这是你修复bug后的方法:
Future<void> methodToTest() async {
apiResult = await apiCall();
}
我正在尝试为使用 Dio. The Dio response has been mocked using http_mock_adapter 调用 API 的方法编写测试。我的问题是我需要等待 API 调用完成才能继续测试,而且我不能简单地使用 await,因为我正在测试的方法不是异步的。有没有办法等待未从测试中调用的未来?
下面是我所说的示例:
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'));
});
以前,当我遇到这种情况时,我可以使用 Future.delayed(Duration.zero)
,但它似乎一直是一种解决方法,但现在它不起作用。
the method I'm testing isn't asynchronous
恭喜,您的测试发现了一个错误。
这是你修复bug后的方法:
Future<void> methodToTest() async {
apiResult = await apiCall();
}