首页 > 解决方案 > 颤振测试仅适用于泵送持续时间

问题描述

我有这个小部件:

class _DemoWidget extends State<DemoWidget> {
  Choices? _selectedChoice;

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          createTile(
              'The First Option', Choices.FRIENDS, const Key('firstOption')),
          if (_selectedChoice == Choices.FIRST)
            TextFormField(
              key: const Key('searchFirst'),
            ),
          createTile('The Second Option', Choices.CONTACT, const Key('secondOption')),
          if (_selectedChoice == Choices.SECOND)
            TextFormField(
              key: const Key('searchSecond'),
            ),
        ],
      ),
    );
  }

  RadioListTile<Choices> createTile(String title, Choices choice, Key key) {
    return RadioListTile<Choices>(
      key: key,
      title: Text(
        title,
      ),
      value: choice,
      groupValue: _selectedChoice,
      onChanged: (Choices? val) => setState(() => _selectedChoice = val),
    );
  }
}

它有两个单选按钮,根据当前处于活动状态的按钮,它将在该选项下方呈现一个文本字段。我正在尝试为此行为创建测试并从以下开始:

  testWidgets('Clicking on person search opens up textfield',
      (WidgetTester tester) async {
    await tester.pumpWidget(
      renderWith(),
    );
    Finder firstOption = find.text('The First Option');
    await tester.tap(firstOption);
    expect(find.byKey(const Key('searchFirst')), findsOneWidget);
  }, skip: false);

但每次都会得到一个失败的测试,然后我在点击和确保可见之间添加了一个持续时间

  testWidgets('Clicking on person search opens up textfield',
      (WidgetTester tester) async {
    await tester.pumpWidget(
      renderWith(),
    );
    Finder firstOption = find.text('The First Option');
    await tester.tap(firstOption);
    await tester.pump(Duration(milliseconds: 50));
    tester.ensureVisible(find.byKey(const Key('searchFirst')));
    expect(find.byKey(const Key('searchFirst')), findsOneWidget);
  }, skip: false);

并且测试通过了。

我认为使用超时似乎不是一种非常安全的测试方法,但在某些地方已经读到某些颤振小部件需要这样做。有没有什么方法可以做这个测试,而不必在测试仪中等待时间?

标签: flutterdarttesting

解决方案


根据 Flutter 文档,您只需要使用pump

Finder firstOption = find.text('The First Option');
await tester.tap(firstOption);
await tester.pump();

推荐阅读