繁体   English   中英

如何对 Flutter TextFormField maxlines 进行单元测试

[英]How to unit Test a Flutter TextFormField maxlines

是否可以编写一个单元测试来验证 TextFormField 的 maxLines 属性是否设置正确。 我找不到访问该属性的方法:

我创建了一个 TextFormField

final field = TextFormField(
    initialValue: "hello",
    key: Key('textformfield'),
    maxLines: 2,
  );

然后在测试中我可以使用 tester.widget 访问表单字段

 final formfield =
    await tester.widget<TextFormField>(find.byKey(Key('textformfield')));

但是由于 maxLines 属性被传递给返回文本字段的生成器,我如何才能访问文本字段。

或者是否有完全其他的方法来验证这一点?

我不知道这是否是一个好的解决方案,但是当我设置我的 TextFormField 的值时,我可以直接找到 EditableText 小部件。 这个小部件的我可以找到测试属性 maxLines。

final EditableText formfield =
   tester.widget<EditableText>(find.text('testvalue'));

expect(formfield.maxLines, 2);

您看不到maxLinesmaxLength等属性的原因是因为它们属于TextField类。

看看源文件中TextFormField构造函数的文档:

  /// Creates a [FormField] that contains a [TextField].
  ///
  /// When a [controller] is specified, [initialValue] must be null (the
  /// default). If [controller] is null, then a [TextEditingController]
  /// will be constructed automatically and its `text` will be initialized
  /// to [initialValue] or the empty string.
  ///
  /// For documentation about the various parameters, see the [TextField] class
  /// and [new TextField], the constructor.

不幸的是,您无法从TextFormField检索TextField对象,您必须通过查找器找到TextField对象。

假设您有一个包含 2 个字段的表单 - 名字和姓氏。 您需要做的是找到TextField类型的所有小部件,将它们添加到列表中,然后您可以遍历列表中的每个元素并运行测试。 这是一个例子:

  testWidgets('Form fields have the correct maximum length and number of lines',
      (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      home: Scaffold(
        body: Form(
          child: Column(
            children: <Widget>[
              TextFormField(
                key: Key('first_name'),
                decoration: InputDecoration(hintText: 'First name'),
                maxLines: 1,
                maxLength: 50,
                obscureText: true,
              ),
              TextFormField(
                key: Key('last_name'),
                decoration: InputDecoration(hintText: 'Last name'),
                maxLines: 1,
                maxLength: 25,
              ),
            ],
          ),
        ),
      ),
    ));

    List<TextField> formFields = List<TextField>();

    find.byType(TextField).evaluate().toList().forEach((element) {
      formFields.add(element.widget);
    });

    formFields.forEach((element) {
      expect(element.maxLines, 1);

      switch (element.decoration.hintText) {
        case 'First name':
          expect(element.maxLength, 50);
          break;

        case 'Last name':
          expect(element.maxLength, 25);
          break;
      }
    });
  });

如果你只有一个字段,你可以这样做:

TextField textField = find.byType(TextField).evaluate().first.widget as TextField;

expect(textField.maxLines, 1);
expect(textField.maxLength, 50);

您可以使用集成测试对其进行测试。 逻辑是在 TextFormField 中输入更多文本,而不是预期的文本。
所以我们可以验证 TextFormField 只允许 2 个字符,如下所示。
例如组件:

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: SingleChildScrollView(
          child: MyLoginPage(title: 'Flutter Demo Home Page'),
        ),
      ),
    );
  }
}

class MyLoginPage extends StatefulWidget {
  MyLoginPage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyLoginPageState createState() => _MyLoginPageState();
}

class _MyLoginPageState extends State<MyLoginPage> {
  String _email;
  String _password;
  TextStyle style = TextStyle(fontSize: 25.0);

  @override
  Widget build(BuildContext context) {
    final emailField = TextField(
      key: Key('textformfield'),
      obscureText: false,
      maxLength: 2,
      style: style,
      decoration: InputDecoration(
          contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          prefixIcon: Icon(FontAwesomeIcons.solidEnvelope),
          hintText: "Email",
          focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.red[300], width: 32.0),
              borderRadius: BorderRadius.circular(97.0))),
      onChanged: (value) {
        setState(() {
          _email = value;
        });
      },
    );
    final passwordField = TextField(
      obscureText: true,
      style: style,
      decoration: InputDecoration(
          contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          prefixIcon: Icon(FontAwesomeIcons.key),
          hintText: "Password",
          focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.red[300], width: 32.0),
              borderRadius: BorderRadius.circular(25.0))),
      onChanged: (value) {
        setState(() {
          _password = value;
        });
      },
    );

    return Center(
      child: Column(
        children: <Widget>[
          Container(
            color: Colors.yellow[300],
            height: 300.0,
          ),
          emailField,
          passwordField,
        ],
      ),
    );
  }
}

考试:

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

import 'package:flutter_textfields_up/main.dart';

void main() {
  testWidgets('Email should be only 2 characters', (WidgetTester tester) async {
    // Build our app and trigger a frame.
    await tester.pumpWidget(MyApp());
    var txtForm = find.byKey(Key('textformfield'));
    await tester.enterText(txtForm, '123');

    expect(find.text('123'), findsNothing); // 3 characters shouldn't be allowed
    expect(find.text('12'), findsOneWidget); // 2 character are valid.

  });
}

请注意我发送了 3 个字符,而 TextFormField 应该只允许 2 个。
希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM