使用颤振集成驱动程序在测试代码中捕获异常

Posted

技术标签:

【中文标题】使用颤振集成驱动程序在测试代码中捕获异常【英文标题】:Catch an exception in the test code using flutter integration driver 【发布时间】:2021-07-13 10:47:43 【问题描述】:

我正在使用 Flutter 集成驱动程序来编写 Flutter Web 应用程序的测试用例。页面加载时,系统抛出异常“ImageCodeException: Failed to decode image data”。但是当我执行开发代码本身时,该异常被捕获。

void main()

IntegrationTestWidgetsFlutterBinding.ensureInitialization();

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

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

);

);

尝试/捕捉

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

我尝试了 try/catch , tester.takeException()。但他们没有工作。请问如何在测试代码中捕获异常?

异常详情:widgetTester.Exception被调用,上面的异常将被忽略等等。

【问题讨论】:

【参考方案1】:

你应该重写 FlutterError.onError。下面的示例允许您使用某些消息捕获 FlutterError,可以将其更改为任意异常:

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

【讨论】:

以上是关于使用颤振集成驱动程序在测试代码中捕获异常的主要内容,如果未能解决你的问题,请参考以下文章