1

I do not believe this is a duplicate of this SO issue because the stated solution does not work in my case.

I am not able to properly catch / verify an Exception in my widgetTest and I am not sure why. Instead of handling the Exception, the test actually just fails on the Exception that I am trying to test.

Here is my code:

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;
  });
}
})

Here is my test:

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);
});

When the test is run, this is the error I get:

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'

and if I change the test to be

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

Then I still get

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>

I was thinking that since the function I am mocking returns the exception, and that is caught in the onPressed widget code, that I wouldn't have any problems. Best case scenario, I can catch the occurance of the exception and verify it happened, and worst case I could at least just see that my error text was added to the page... but I'm just getting this error. Am I going about handling errors wrong in Flutter?

Jake Boomgaarden
  • 3,394
  • 1
  • 17
  • 31

0 Answers0