Testing Flutter apps翻译-查找child widget

599 阅读2分钟

翻译首页

为了在测试环境里找到Widgets,我们需要使用Finder类。虽然我们可以编写自己的Finder类,但是通常使用flutter_test包提供的工具查找Widget更方便。

在这个示例里,我们看一下flutter_test包提供的find常量并演示如何使用它提供的一些Finders。如果查看可用finders的完整列表,请查看CommonFinders文档

如果你不熟悉Widget测试和Finder类的使用方法,可以回顾Widget测试介绍

目录:

  1. 查找TextWidget
  2. 使用一个具体的Key查找一个Widget
  3. 查找一个具体的Widget实例

1. 查找TextWidget

在我们的测试里,我们经常需要查找包含具体文本的Widget。这正是find.text方法的用途。它将会创建一个Finder然后搜索显示指定字符串的Text。

testWidgets('finds a Text Widget', (WidgetTester tester) async {
  // Build an App with a Text Widget that displays the letter 'H'
  await tester.pumpWidget(MaterialApp(
    home: Scaffold(
      body: Text('H'),
    ),
  ));

  // Find a Widget that displays the letter 'H'
  expect(find.text('H'), findsOneWidget);
});

2. 使用一个具体的Key查找一个Widget

有时候,我们可能想要根据已经提供给Widget的Key来查找Widget。在我们显示了很多相同Widget的时候使用这种方法很方便。例如,我们可能有一个ListView列表,显示了一些包含相同文本的Text Widget。

在这个示例里,我们可以给列表里的每个Widget都提供一个Key。这将允许我们唯一标识一个具体的Widget,这样我们在测试环境里查找Widget将更加容易。

testWidgets('finds a Widget using a Key', (WidgetTester tester) async {
  // Define our test key
  final testKey = Key('K');

  // Build a MaterialApp with the testKey
  await tester.pumpWidget(MaterialApp(key: testKey, home: Container()));

  // Find the MaterialApp Widget using the testKey
  expect(find.byKey(testKey), findsOneWidget);
});

总结:

flutter_test包给我们提供的find常量给我们提供了一些在测试环境查找Widget的方法,另外还有一些用于不同用途的方法。 如果上述例子不适用于一些特殊用例,请查看CommonFinders文档并学习更多用法。

完整示例:

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

void main() {
  testWidgets('finds a Text Widget', (WidgetTester tester) async {
    // Build an App with a Text Widget that displays the letter 'H'
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        body: Text('H'),
      ),
    ));

    // Find a Widget that displays the letter 'H'
    expect(find.text('H'), findsOneWidget);
  });

  testWidgets('finds a Widget using a Key', (WidgetTester tester) async {
    // Define our test key
    final testKey = Key('K');

    // Build a MaterialApp with the testKey
    await tester.pumpWidget(MaterialApp(key: testKey, home: Container()));

    // Find the MaterialApp Widget using the testKey
    expect(find.byKey(testKey), findsOneWidget);
  });

  testWidgets('finds a specific instance', (WidgetTester tester) async {
    final childWidget = Padding(padding: EdgeInsets.zero);

    // Provide our childWidget to the Container
    await tester.pumpWidget(Container(child: childWidget));

    // Search for the childWidget in the tree and verify it exists
    expect(find.byWidget(childWidget), findsOneWidget);
  });
}