Flutter小部件测试-等待将来完成

时间:2018-12-07 14:49:36

标签: flutter

我有一个窗口小部件测试,该测试会抽动被测试的窗口小部件, 并在其打开时执行后台操作(staticWrapper.requestPermission()),该操作将返回Future并根据其结果设置状态。 问题是测试没有等待这个将来完成的测试代码:

/// When micro permission denied, should show error message.
testWidgets('When micro permission denied, should show error message.',
    (WidgetTester tester) async {
  when(staticWrapper.requestPermission(Permission.RecordAudio))
      .thenAnswer((_) => Future.value(PermissionStatus.denied));
  await tester.pumpWidget(widget);
  final loginText = find.text(callScreen_microPermissionDenied);
  expect(loginText, findsOneWidget);
});

受影响的小部件代码:

void _requestMicroPermission() async {
final result =
    await staticWrapper.requestPermission(Permission.RecordAudio);
debugPrint("Microphone permission status: $result");
if (result == PermissionStatus.authorized) {
  native.init();
} else {
  setState(() {
    _loginText = tnsManager.getText(TranslationsManager.callScreen_microPermissionDenied);
  });
}

}

expect()方法在setState()调用之前被调用。

有帮助吗?

1 个答案:

答案 0 :(得分:0)

最后,我使用WidgetTester#pumpAndSettle()解决了该问题:

testWidgets('When micro permission denied, should show error message.',
    (WidgetTester tester) async {
  when(staticWrapper.requestPermission(Permission.RecordAudio))
      .thenAnswer((_) => Future.value(PermissionStatus.denied));
  await tester.pumpWidget(widget);
  await tester.pump();
  final loginText = find.text(callScreen_microPermissionDenied);
  expect(loginText, findsOneWidget);
});