Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Testing for exceptions in widget tests

How do I go about making sure the ui (widget) throws an exception during widget testing in Flutter. Here is my code that does not work:

expect(
  () => tester.tap(find.byIcon(Icons.send)),
  throwsA(const TypeMatcher<UnrecognizedTermException>()),
);

It fails with the following error

...
Expected: throws <Instance of 'TypeMatcher<UnrecognizedTermException>'>
  Actual: <Closure: () => Future<void>>
   Which: returned a Future that emitted <null>

OR......should I be testing how the UI handles an exception by looking for error messages, etc??

like image 870
xpeldev Avatar asked Jan 18 '19 22:01

xpeldev


People also ask

How do you test a stateful widget in flutter?

For that, we will use a widget tester to tap the submit button and Mockito's verify method. The snippet is the same for both create and update tests. final saveButton = find. byKey(const Key('submit-button')); expect(saveButton, findsOneWidget); await tester.

What is exception flutter?

The user may enter an incorrect input, a network request may fail, or we could have made a programmer mistake somewhere, and our app will crash. Exception handling is a way of dealing with these potential errors in our code so our app can gracefully recover from them.


1 Answers

To catch exceptions thrown in a flutter test, use WidgetTester.takeException. This returns the last exception caught by the framework.

await tester.tap(find.byIcon(Icons.send));
expect(tester.takeException(), isInstanceOf<UnrecognizedTermException>());

You also don't need a throwsA matcher, since it is not being thrown from the method.

like image 153
Jonah Williams Avatar answered Sep 19 '22 18:09

Jonah Williams