Catch an exception in the test code using flutter integration driver

Issue

I am using the flutter integration driver to write the test cases for flutter web application. When the page is loading, the system throws an exception as "ImageCodeException: Failed to decode image data". But when I execute the dev code itself, that exception is caught.

void main(){

IntegrationTestWidgetsFlutterBinding.ensureInitialization();

group('Test scenario .....',(){
testWidgets('Home',(WidgetTester tester)asynsc{

app.main(); // exception throws calling this line
tester.pumpAndSettle();

});

});

try/catch

void main(){
    
    IntegrationTestWidgetsFlutterBinding.ensureInitialization();
    
    group('Test scenario .....',(){
    testWidgets('Home',(WidgetTester tester)asynsc{
    
try{
    app.main(); // exception throws calling this line
catch(Exception){}
    tester.pumpAndSettle();
    
    });
    
    });

tester.takeException

void main(){
    
    IntegrationTestWidgetsFlutterBinding.ensureInitialization();
    
    group('Test scenario .....',(){
    testWidgets('Home',(WidgetTester tester)asynsc{
    
tester.takeException()  // or
    app.main(); // exception throws calling this line
tester.takeException()  // or
    tester.pumpAndSettle();
    
    });
    
    });

I tried with try/catch , tester.takeException(). But they did not work. How can I catch an exception in the test code, please ?

Exception details : widgetTester.Exception is called , the above exception will be ignored etc..

Solution

You should override FlutterError.onError. An example below, that allows you to catch FlutterError with certain messages, can be changed to arbitrary exceptions:

  FlutterError.onError = (FlutterErrorDetails data) {
    if (data.exception is FlutterError) {
      final fErr = data.exception as FlutterError;
      if (fErr.message == '...') {
        // do not forward to presentError
        return;
      }
    }
    FlutterError.presentError(data);
  };

Answered By – jangruenwaldt

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *