如何在Flutter中测试Cupertino Picker

时间:2018-11-20 17:12:23

标签: dart flutter flutter-test

我正在编写小部件,以测试库珀蒂诺(Cupertino)拾纸器针对用户所选择的不同值。我找不到任何好的教程。我遵循了此https://github.com/flutter/flutter/blob/master/packages/flutter/test/cupertino/picker_test.dart,但这不适用于我的情况。在我的情况下,当用户从picker中选择值时,测试用例应检查用户选择的是正确值还是默认值。

Cupertino Picker代码:

List<String> ages1 = ["-- select --"];

List<String> ages2 = List<String>.generate(
    45, (int index) => (21 + index).toString(),
    growable: false);

List<String> ages = [ages1, ages2].expand((f) => f).toList();
picker.dart:
  Widget _buildAgePicker(BuildContext context) {
    final FixedExtentScrollController scrollController =
        FixedExtentScrollController(initialItem: _selectedAgeIndex);

    return GestureDetector(
      key: Key("Age Picker"),
      onTap: () async {
        await showCupertinoModalPopup<void>(
          context: context,
          builder: (BuildContext context) {
            return _buildBottomPicker(
              CupertinoPicker(
                key: Key("Age picker"),
                scrollController: scrollController,
                itemExtent: dropDownPickerItemHeight,
                backgroundColor: Theme.of(context).canvasColor,
                onSelectedItemChanged: (int index) {
                  setState(() {
                    _selectedAgeIndex = index;
                    ageValue = ages[index];
                    if (ageValue == S.of(context).pickerDefaultValue) {
                      ageDividerColor = Theme.of(context).errorColor;
                      errorText = S.of(context).pickerErrorMessage;
                      ageDividerWidth = 1.2;
                    } else {
                      ageDividerColor = Colors.black87;
                      errorText = "";
                      ageDividerWidth = 0.4;
                    }
                  });
                },
                children: List<Widget>.generate(ages.length, (int index) {
                  return Center(
                    child: Text(ages[index]),
                  );
                }),
              ),
            );
          },
        );
      },
      child: _buildMenu(
        <Widget>[
          Text(
            S.of(context).Age,
            style: TextStyle(fontSize: 17.0),
          ),
          Text(
            ages[_selectedAgeIndex],
          ),
        ],
      ),
    );
  }
 Widget _buildMenu(List<Widget> children) {
    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).canvasColor,
      ),
      height: 44.0,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        child: SafeArea(
          top: false,
          bottom: false,
          child: DefaultTextStyle(
            style: const TextStyle(
              color: Colors.black,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: children,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBottomPicker(Widget picker) {
    return Container(
      height: dropDownPickerSheetHeight,
      padding: const EdgeInsets.only(top: 6.0),
      color: Theme.of(context).canvasColor,
      child: DefaultTextStyle(
        style: const TextStyle(
          color: Colors.black,
          fontSize: 22.0,
        ),
        child: GestureDetector(
          key: Key("picker"),
          onTap: () {},
          child: SafeArea(
            top: false,
            child: picker,
          ),
        ),
      ),
    );
  }

测试代码:

testWidgets("picker test",(WidgetTester tester)async{
   await tester.tap(find.byKey(Key("Age Picker")));

   await tester.drag(find.byKey(Key("Age Picker")), Offset(0.0,70.0));

   await tester.pumpAndSettle();

   expect(ages[1], "21");
});

1 个答案:

答案 0 :(得分:0)

您收到什么错误?我尝试从您提供的CupertinoPicker代码段创建最小复制,我确实在testWidgets()中遇到了一些问题。

我注意到的一些问题是CupertinoPicker的键为“ Age Picker”,而GestureDetector的键集为“ Age Picker”。请注意,密钥区分大小写。由于您要测试CupertinoPicker,因此似乎没有必要在GestureDetector上设置密钥。

除此之外,该测试未构建任何小部件。建议您通过官方文档进行Flutter测试,以开始使用https://flutter.dev/docs/cookbook/testing/widget/introduction

这是我根据您提供的代码片段创建的副本。

测试小部件的代码

void main(){
  var ages = [18, 19, 20, 21, 22, 24, 24, 25];
  testWidgets("CupertinoPicker test", (WidgetTester tester) async {
    // build the app for the test
    // https://flutter.dev/docs/cookbook/testing/widget/introduction#4-build-the-widget-using-the-widgettester
    await tester.pumpWidget(MyApp());

    // key should match the key set in the widget
    await tester.tap(find.byKey(Key("Age Picker")));

    await tester.drag(find.byKey(Key("Age Picker")), Offset(0.0, 70.0));

    await tester.pumpAndSettle();

    expect(ages[3], 21);
  });
}

该应用的示例代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child:
        testPicker(),
      ),
    );
  }

  var _selectedAgeIndex = 0;
  var scrollController = FixedExtentScrollController();
  var dropDownPickerItemHeight = 50.0;
  var ageValue;
  var ages = [18, 19, 20, 21, 22, 24, 24, 25];
  testPicker(){
    return CupertinoPicker(
      key: Key("Age Picker"),
      scrollController: scrollController,
      itemExtent: dropDownPickerItemHeight,
      backgroundColor: Theme.of(context).canvasColor,
      onSelectedItemChanged: (int index) {
        setState(() {
          _selectedAgeIndex = index;
          ageValue = ages[index];
          print('CupertinoPicker age[$index]: ${ages[index]}');
          // if (ageValue == S.of(context).pickerDefaultValue) {
          //   ageDividerColor = Theme.of(context).errorColor;
          //   errorText = S.of(context).pickerErrorMessage;
          //   ageDividerWidth = 1.2;
          // } else {
          //   ageDividerColor = Colors.black87;
          //   errorText = "";
          //   ageDividerWidth = 0.4;
          // }
        });
      },
      children: List<Widget>.generate(ages.length, (int index) {
        return Center(
          child: Text('${ages[index]}'),
        );
      }),
    );
  }
}