【问题标题】:How can I make a widget test of this method?如何对此方法进行小部件测试?
【发布时间】:2022-01-21 04:22:56
【问题描述】:
    showAlertDialog(BuildContext context, AlertDialog alert, bool dismissible) {
    if (isDialogOpened!) {
      Navigator.pop(context);
      isDialogOpened = false;
    }
    showDialog(
      barrierDismissible: dismissible,
      context: context,
      builder: (BuildContext context) {
        isDialogOpened = true;
        return alert;
      },
    ).then((_) => isDialogOpened = false);
  }

这个方法在我称为 AlertController 的控制器中,在我的控制器中,我不知道用这种方法进行测试的最佳方法是什么。

【问题讨论】:

    标签: flutter dart flutter-test


    【解决方案1】:

    我不确定您要测试哪些属性,但这是一个示例测试,它将检查 isDialogOpened 变量是否更改状态。希望这能为您的测试提供一个良好的起点:

    import 'package:flutter/material.dart';
    import 'package:flutter_test/flutter_test.dart';
    
    bool? isDialogOpened = false;
    showAlertDialog(BuildContext context, AlertDialog alert, bool dismissible) {
      if (isDialogOpened!) {
        Navigator.pop(context);
        isDialogOpened = false;
      }
      showDialog(
        barrierDismissible: dismissible,
        context: context,
        builder: (BuildContext context) {
          isDialogOpened = true;
          return alert;
        },
      ).then((_) => isDialogOpened = false);
    }
    
    void main() {
      testWidgets('test showAlertDialog function', (WidgetTester tester) async {
        final scaffoldKey = GlobalKey<ScaffoldState>();
    
        await tester.pumpWidget(MaterialApp(
          home: Scaffold(
            key: scaffoldKey,
            appBar: AppBar(title: const Text('Test App')),
          ),
        ));
    
        expect(isDialogOpened, false);
    
        showAlertDialog(
          scaffoldKey.currentContext!,
          AlertDialog(
            title: const Text('Custom Dialog'),
            actions: [
              Builder(
                builder: (context) => IconButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  icon: const Icon(Icons.close),
                ),
              ),
            ],
          ),
          true,
        );
        
        await tester.pump();
        expect(isDialogOpened, true);
    
        await tester.tap(find.byIcon(Icons.close));
        await tester.pump();
        expect(isDialogOpened, false);
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多