0

我不相信这是这个 SO 问题的重复,因为所述解决方案在我的情况下不起作用。

我无法在我的 widgetTest 中正确捕获/验证异常,我不知道为什么。测试实际上只是在我尝试测试的异常上失败,而不是处理异常。

这是我的代码:

child: ElevatedButton(
  onPressed: () {
try {
  bool loggedIn = await widget.authHandler.login(email, password);
} on InvalidStateException catch (e) {
  setState(() {
    errorMessage = 'Error Logging In. Please Try Again';
    loginError = true;
  });
}
})

这是我的测试:

testWidgets('Testing Login button Failure - Exception Thrown',
        (tester) async {
      final amplifyAuthMock = MockAmplifyAuth();
      when(amplifyAuthMock.login('test@test.com', 'password!'))
          .thenThrow(InvalidStateException);
      await tester.pumpWidget(createLoginForm(amplifyAuthMock));
      await inputDummyLoginText(tester);
      await tester.tap(find.byType(ElevatedButton));
      expect(tester.takeException(), isInstanceOf<InvalidStateException>());
      await tester.pumpAndSettle(const Duration(seconds: 1));
      expect(find.text('Error Logging In. Please Try Again'), findsOneWidget);
});

运行测试时,这是我得到的错误:

The following TestFailure object was thrown running a test (but after the test had completed):
  Expected: <Instance of 'InvalidStateException'>
  Actual: <null>
   Which: is not an instance of 'InvalidStateException'

如果我将测试更改为

expect(() async => await tester.tap(find.byType(SkillTreeElevatedButton)), throwsA(isA<InvalidStateException>()));

然后我仍然得到

The following TestFailure object was thrown running a test (but after the test had completed):
  Expected: throws <Instance of 'InvalidStateException'>
  Actual: <Closure: () => Future<void>>
   Which: returned a Future that emitted <null>

我在想,由于我正在模拟的函数返回异常,并且它被捕获在 onPressed 小部件代码中,所以我不会有任何问题。最好的情况是,我可以捕捉到异常的发生并验证它是否发生,最坏的情况是我至少可以看到我的错误文本已添加到页面中......但我只是收到了这个错误。我要在 Flutter 中错误地处理错误吗?

4

0 回答 0