Testing your app's error handling is super important. Sometimes, a widget might throw an error under certain conditions, and you need to make sure it happens correctly and that your app can handle it.
Why Test Errors?
Knowing that your code fails gracefully or throws expected errors helps you build more reliable apps. It confirms your error logic works as intended.
Catching Errors in Widget Tests
In Flutter widget tests, unhandled errors can make your test fail. To check if an error is thrown and what kind of error it is, you can temporarily change how Flutter handles errors during the test.
Here's how you can do it:
testWidgets('creating a widget with some param \u2192 throw', (WidgetTester tester) async {
var exceptionRes;
// Catch Flutter error or this will make your test fail
FlutterError.onError = (details) {
exceptionRes = details.exception;
};
await tester.pumpWidget(MyAppWithError);
// Set Flutter onError back. Flutter will throw if not handled.
FlutterError.onError = (details) \u2192 FlutterError.presentError(details);
// Now you can check the caught error
expect(exceptionRes, isNotNull);
expect(exceptionRes, isInstanceOf<MyCustomException>());
});
Understanding the Code
- We declare a variable
exceptionRes
to store the error. - We temporarily set
FlutterError.onError
to a function that catches thedetails.exception
and saves it toexceptionRes
. - We run the test that should cause the widget to throw an error using
tester.pumpWidget
. - We reset
FlutterError.onError
back to its default behavior (FlutterError.presentError
) so other parts of your test or other tests aren't affected. - We use
expect
to check ifexceptionRes
is not null (meaning an error was caught) and if it's the specific type of exception we expected (MyCustomException
in this example).
Keep it Clean
Remember to always reset FlutterError.onError
after your test is done checking the error. This prevents side effects in other tests.
This simple pattern lets you reliably test error-throwing situations in your Flutter widgets.