Testing Flutter apps翻译-查找child widget

翻译首页bash

为了在测试环境里找到Widgets,咱们须要使用Finder类。虽然咱们能够编写本身的Finder类,可是一般使用flutter_test包提供的工具查找Widget更方便。async

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

若是你不熟悉Widget测试和Finder类的使用方法,能够回顾Widget测试介绍工具

目录:post

  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将更加容易。ui

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文档并学习更多用法。spa

完整示例:

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);
  });
}
复制代码
相关文章
相关标签/搜索