我想测试一些小部件的属性,但找不到简单的方法。
这是一个带有密码字段的简单示例,如何检查obscureText是否设置为true?
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const darkBlue = Color.fromARGB(255, 18, 32, 47);
Future<void> main() async {
testWidgets('Wheelio logo appear on the login screen',
(WidgetTester tester) async {
final Key _formKey = GlobalKey<FormState>();
final TextEditingController passwordController = TextEditingController();
const Key _passwordKey = Key('PASSWORD_KEY');
final Finder passwordField = find.byKey(_passwordKey);
await tester.pumpWidget(MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Form(
key: _formKey,
child: TextFormField(
key: _passwordKey,
obscureText: true,
controller: passwordController,
),
),
),
),
));
await tester.pump();
expect(passwordField, findsOneWidget);
final TextFormField myPasswordWidget =
tester.widget(passwordField) as TextFormField;
// How can I check that obscureText property is set to true ?
});
}
答案 0 :(得分:2)
您可以使用tester
和find
在小部件树中获取任何内容。
例如,如果要测试Text
的属性textAlign
设置为TextAlign.center
,则可以执行以下操作:
expect(
tester.widget(find.byType(Text)),
isA<Text>().having((t) => t.textAlign, 'textAlign', TextAlign.center),
);
答案 1 :(得分:0)
CommonFinders byWidgetPredicate method
final _passwordKey = GlobalKey(debugLabel: 'PASSWORD_KEY');
await tester.pumpWidget(
// ...
);
bool isObscureTextTrue(TextFormField widget) {
final TextField textField = widget.builder(_passwordKey.currentState);
return textField.obscureText;
}
final finder = find.byWidgetPredicate(
(widget) => widget is TextFormField && isObscureTextTrue(widget),
);
expect(finder, findsOneWidget);
答案 2 :(得分:0)
您可以通过Finder获取小部件。
TabBar tabBar = find.byType(TabBar).evaluate().single.widget as TabBar
答案 3 :(得分:0)
final passwordField = find.byKey(_passwordKey);
final input = tester.firstWidget<TextFormField>(passwordField);
input
将成为您的小部件,因此您现在可以检查
expect(input.obscureText, true);