使用 flutter integration driver 在测试代码中捕获异常

Catch an exception in the test code using flutter integration driver

我正在使用 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();

});

});

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

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

异常详细信息:widgetTester.Exception 被调用,上述异常将被忽略等。

您应该覆盖 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);
  };