Flutter 驱动程序:测试BottomNavigationBarItem

bas*_*god 7 dart flutter flutter-test

我如何通过FlutterDriver测试BottomNavigationBarItems

FlutterDriver允许通过textbyValueKeybyTooltipbyType访问小部件。

但是由于以下原因,这些方法都不适用于我的应用程序:

  • text:该应用程序已本地化,我需要以多种语言测试该应用程序。

  • byValueKey:BottomNavigationBarItems 没有关键属性。

  • byTooltip:BottomNavigationBarItems 没有toolTip属性。

  • byType : byType 只返回类型的第一个匹配项,没有列表(需要,因为我有多个选项卡)。

非常感谢!

干杯。

Kam*_*oda 6

正如 @bsr 和 @user12563357 所提到的 - 您可以使用文本小部件上的

bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.shifting,
        key: Key('bottom'),
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.ac_unit),
            title: Text('First', key: Key('first'),)
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.cast),
            title: Text('Second', key: Key('second'),)
          )
        ],
      ),
Run Code Online (Sandbox Code Playgroud)

并找到要单击测试中的栏项的文本:

final firstItem = find.byValueKey('first');
await driver.tap(firstItem);
Run Code Online (Sandbox Code Playgroud)

顺便说一句:您还可以使用find.ancestor找到 BottomNavigationBarItem

find.ancestor(of: firstItem, matching: find.byType("BottomNavigationBarItem"));
Run Code Online (Sandbox Code Playgroud)

但你不能点击它。


Dar*_*han 5

不确定您是否找到了这个问题的答案,但我将在这里发布一个对我有用的解决方案。基本上,BottomNavigationBar有一个key你需要使用的属性。一旦 Flutter Driver 识别出这个键,你就可以告诉 driver 点击它的任何子项,即BottomNavigationBarItem.

我的屏幕有 2 个bottomNavigationBarItems,如下所示,我为它们的父小部件定义了键,即BottomNavigationBar

bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.shifting,
        key: Key('bottom'),
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.ac_unit, color: Colors.green,),
            title: Text('First', style: TextStyle(color: Colors.black),)
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.cast, color: Colors.yellow,),
            title: Text('Second', style: TextStyle(color: Colors.black),)
          )
        ],
      ),
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我编写了一个颤振驱动程序测试来利用这两个完美运行的项目。

test('bottomnavigationbar test', () async {
      await driver.waitFor(find.byValueKey('bottom'));
      await driver.tap(find.text('First'));
      print('clicked on first');
      await driver.tap(find.text('Second'));
      print('clicked on second too');
    });
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明

  • @basedgod 我们不能在文本小部件上使用 key 吗?``` BottomNavigationBarItem( icon: Icon( Icons.settings), title: Text( 'Settings', key: const Key('settings'), ),``` 它似乎对我有用。 (2认同)