选择其他项目时,Flutter小部件测试不会触发DropdownButton.onChanged

时间:2020-10-22 20:26:28

标签: flutter flutter-web flutter-test

我正在编写Flutter Web应用程序,并将一些小部件测试添加到我的代码库中。我难以按预期进行flutter_test的工作。我目前面临的问题是尝试在DropdownButton中选择一个值。

下面是重现该问题的完整的窗口小部件测试代码:

void main() {
  group('description', () {
    testWidgets('description', (WidgetTester tester) async {
      await tester.pumpWidget(MaterialApp(
        home: Card(
          child: Column(
            children: [
              Expanded(
                child: DropdownButton(
                  key: Key('LEVEL'),
                  items: [
                    DropdownMenuItem<String>(
                      key: Key('Greater'),
                      value: 'Greater',
                      child: Text('Greater'),
                    ),
                    DropdownMenuItem<String>(
                      key: Key('Lesser'),
                      value: 'Lesser',
                      child: Text('Lesser'),
                    ),
                  ],
                  onChanged: (value) {
                    print('$value');
                  },
                  value: 'Lesser',
                ),
              )
            ],
          ),
        ),
      ));

      expect((tester.widget(find.byKey(Key('LEVEL'))) as DropdownButton).value,
          equals('Lesser'));

      await tester.tap(find.byKey(Key('LEVEL')));

      await tester.tap(find.byKey(Key('Greater')));
      await tester.pumpAndSettle();

      expect((tester.widget(find.byKey(Key('LEVEL'))) as DropdownButton).value,
          equals('Greater'));
    });
  });
}

此测试未能达到最终期望-expect(widget.value, equals('Greater'));

正如我在调试器中看到的那样,或者在输出中寻找我的print语句时,永远不会调用onChanged回调。

测试DropdownButton行为的神奇之处是什么?

1 个答案:

答案 0 :(得分:0)

尽管测试很重要,但在与用户交互相关的任何代码之后添加tester.pump()调用。

下拉按钮的测试与普通小部件略有不同。对于所有情况,最好参考here,它是下拉按钮的实际测试。

测试时有些提示。

  1. DropdownButton由用于按钮的'IndexedStack'和用于菜单项列表的普通堆栈组成。
  2. 以某种方式为上述堆栈中的两个小部件提供了为DropDownMenuItem分配的键和文本。
  3. 在点击时选择返回的小部件列表中的最后一个元素。
  4. 下拉按钮还需要一些时间进行动画处理,因此我们根据颤振的参考测试中的建议两次调用tester.pump
  5. value的{​​{1}}属性不会自动更改。必须使用DropdownButton进行设置。因此,最后的断言行是错误的,除非将测试用here之类的setState包装,否则测试将无效。

有关如何使用StatefulBuilder的更多详细信息,请选中此post

DropDownButton