Тест виджета Flutter Listview не работает, текст ошибки не найден внутри списка?

Код моего настраиваемого виджета:

    class CustomWidget extends StatefulWidget {

      final int index;
      final String value;
      final bool isSelected;
      final VoidCallback onSelect;

      const CustomWidget({
            Key key,
    @required this.index,
    @required this.value,
    @required this.isSelected,
    @required this.onSelect,
  })  : assert(index != null),
        assert(value != null),
        assert(isSelected != null),
        assert(onSelect != null),
        super(key: key);

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

    class _CustomWidgetState extends State<CustomWidget> {
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTap: widget.onSelect,
          child: Container(
            margin: EdgeInsets.all(5.0),
            child: ListTile(
               title: Text(widget.index == 1 ? " ${widget.value} ${widget.index}" : "${widget.value}" ),
            ),
            decoration: widget.isSelected
                ? BoxDecoration(color: Colors.black38, border: Border.all(color: Colors.black))
                : BoxDecoration(),
          ),
        );
      }
    }

Мое приложение с использованием настраиваемого виджета

    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }

    class _MyHomePageState extends State<MyHomePage> {
      int currentSelectedIndex;
 List<ListModel> _list = [
    ListModel(
      text: "Flutter.dev",
      index: 0,
    ),
    ListModel(
      text: "Inducesmile.com",
      index: 1,
    ),
    ListModel(
      text: "Google.com",
      index: 2,
    ),
    ListModel(
      text: "Yahoo.com",
      index: 3,
    ),
  ];

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Selected index is $currentSelectedIndex'),
          ),
          body: ListView.builder(
            itemCount: _list.length,
            itemBuilder: (context, index) {
              return CustomWidget(
                index: index,
                value: _list[index].text,
                isSelected: currentSelectedIndex == index,
                onSelect: () {
                  setState(() {
                    currentSelectedIndex = index;
                  });
                },
              );
            },
          ),
        );
      }
    }

Код ListModel:

class ListModel {
  String text;
  int index;
  ListModel({this.text, this.index});
}

Тестовый код виджета, который я пробовал

 testWidgets("Find text", (WidgetTester tester) async {
    final testableWidget = MyApp();
    await tester.pumpWidget(testableWidget);
    expect(find.widgetWithText(CustomWidget,"Inducesmile.com 1"), findsOneWidget);
  });

Сообщение об ошибке:

    Error: The following TestFailure object was thrown running a test:
      Expected: exactly one matching node in the widget tree
      Actual: ?:<zero widgets with type "CustomWidget" which is an ancestor of text "Inducesmile.com 1">
When the exception was thrown, this was the stack:
#4      main.<anonymous closure> (file:///Users/testUser/Documents/my_app/test/widget_test.dart:23:5)
<asynchronous suspension>
#5      testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:82:23)
#6      TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:571:19)
<asynchronous suspension>
#9      TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:555:14)

Что: означает, что ничего не найдено, но ожидалось

Как я могу нажать на конкретный элемент списка и убедиться, что элемент, который он содержит, есть в виджете или нет? Я также хочу проверить количество элементов в списке? Но даже не найти простого текста


person pak karachi    schedule 15.05.2019    source источник
comment
опубликуйте ошибку журнала, пожалуйста.   -  person Augusto    schedule 15.05.2019
comment
ошибка журнала добавлена ​​сейчас   -  person pak karachi    schedule 15.05.2019


Ответы (2)


Я была такая же проблема. У меня был собственный виджет внутри listview, и мне нужно было протестировать виджет внутри дочерних элементов listview.

Вначале я позвонил:

debugDumpApp()

чтобы увидеть, существует ли виджет в дереве виджетов. (и он действительно существовал)

Позже я обнаружил, что вам нужно установить для shrinkWrap значение true в ListView. и это сработало

person Chloe H    schedule 22.04.2020

Можете ли вы попробовать вот так:

ListModel (key: Key ("Inducesmile"), текст: "Inducesmile.com", index: 1,),

А потом

ожидать (find.byKey (Key ("Inducesmile")), findOneWidget);

person camillo777    schedule 10.06.2020