簡體   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