【发布时间】:2021-10-23 08:42:15
【问题描述】:
我有这个小部件:
class _DemoWidget extends State<DemoWidget> {
Choices? _selectedChoice;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
createTile(
'The First Option', Choices.FRIENDS, const Key('firstOption')),
if (_selectedChoice == Choices.FIRST)
TextFormField(
key: const Key('searchFirst'),
),
createTile('The Second Option', Choices.CONTACT, const Key('secondOption')),
if (_selectedChoice == Choices.SECOND)
TextFormField(
key: const Key('searchSecond'),
),
],
),
);
}
RadioListTile<Choices> createTile(String title, Choices choice, Key key) {
return RadioListTile<Choices>(
key: key,
title: Text(
title,
),
value: choice,
groupValue: _selectedChoice,
onChanged: (Choices? val) => setState(() => _selectedChoice = val),
);
}
}
它有两个单选按钮,根据当前处于活动状态的按钮,它将在该选项下方呈现一个文本字段。我正在尝试为此行为创建测试并从以下开始:
testWidgets('Clicking on person search opens up textfield',
(WidgetTester tester) async {
await tester.pumpWidget(
renderWith(),
);
Finder firstOption = find.text('The First Option');
await tester.tap(firstOption);
expect(find.byKey(const Key('searchFirst')), findsOneWidget);
}, skip: false);
但每次测试都会失败,然后我在点击和确保可见之间添加了一个持续时间
testWidgets('Clicking on person search opens up textfield',
(WidgetTester tester) async {
await tester.pumpWidget(
renderWith(),
);
Finder firstOption = find.text('The First Option');
await tester.tap(firstOption);
await tester.pump(Duration(milliseconds: 50));
tester.ensureVisible(find.byKey(const Key('searchFirst')));
expect(find.byKey(const Key('searchFirst')), findsOneWidget);
}, skip: false);
测试通过了。
我认为使用超时似乎不是一种非常安全的测试方式,但在某些地方已经读到某些颤振小部件需要这样做。有没有什么方法可以做这个测试,而不必在测试器中等待时间?
【问题讨论】: