Home > Software engineering >  How to expect that an exception is thrown in flutter widgets test?
How to expect that an exception is thrown in flutter widgets test?

Time:04-28

I have this test:

testWidgets('Controller must only be used with one widget at a time',
    (WidgetTester tester) async {
  final CustomAnimatedWidgetController controller = CustomAnimatedWidgetController();

  await tester.pumpWidget(
    MaterialApp(
      home: Scaffold(
        body: Column(
          children: [
            CustomAnimatedWidget(
              child: Container(),
              controller: controller,
            ),
            CustomAnimatedWidget(// this declaration will throw an exception from initState of this widget
              child: Container(),
              controller: controller,
            ),
          ],
        ),
      ),
    ),
  );

  expect(tester.takeException(), isInstanceOf<Exception>());
});

Which is guaranteed to throw an exception of type Exception (due to using the controller two times), but the expect is not catching the exception. Instead, the test fails and I see my exception thrown in the console.

But here and here they say this is how it must be used. What is wrong with the test?

CodePudding user response:

Looking more into the code of pumpWidget, we see that it returns TestAsyncUtils.guard<void>(...) so the test is running in its own "zone" and that's why the exception was swallowed by the framework (even adding try catch around pumpWidget above didn't catch the error)

The only way I found is override FlutteError.onError function:

FlutterError.onError = (details){
// handle error here
      };

now the test can pass and the error thrown during test are forwarded to this method.

CodePudding user response:

This post answer shows the action to be done by the tester (a click is simulated) that will cause an exception. We can use expect(tester.takeException(), isInstanceOf<AnExceptionClass>()); to ensure that an exception has been thrown as expected.

In your case the Widget cannot be rendered correctly. Widget test should be done with a correctly implemented Widget first.

  • Related