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

时间:2019-04-29 21:46:08

标签: unit-testing testing flutter widget

是否可以编写一个单元测试来验证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属性传递给了返回文本字段的生成器,因此我如何获得对文本字段的访问权限。

还是有其他完全方法可以验证这一点?

3 个答案:

答案 0 :(得分: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.

不幸的是,您无法从TextField检索TextFormField对象,而必须通过查找器找到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);

答案 1 :(得分:1)

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

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

expect(formfield.maxLines, 2);

答案 2 :(得分:0)

您可以使用集成测试对其进行测试。逻辑是在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个字符。
希望有帮助。