我正在编写一个 Flutter Web 应用程序,并向我的代码库添加一些小部件测试。我很难让 flutter_test 按预期工作。我当前面临的问题是尝试在 DropdownButton 中选择一个值。
以下是重现问题的完整小部件测试代码:
void main() {
group('description', () {
testWidgets('description', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Card(
child: Column(
children: [
Expanded(
child: DropdownButton(
key: Key('LEVEL'),
items: [
DropdownMenuItem<String>(
key: Key('Greater'),
value: 'Greater',
child: Text('Greater'),
),
DropdownMenuItem<String>(
key: Key('Lesser'),
value: 'Lesser',
child: Text('Lesser'),
),
],
onChanged: (value) {
print('$value');
},
value: 'Lesser',
),
)
],
),
),
));
expect((tester.widget(find.byKey(Key('LEVEL'))) as DropdownButton).value,
equals('Lesser'));
await tester.tap(find.byKey(Key('LEVEL')));
await tester.tap(find.byKey(Key('Greater')));
await tester.pumpAndSettle();
expect((tester.widget(find.byKey(Key('LEVEL'))) as DropdownButton).value,
equals('Greater'));
});
});
}
这次测试失败了最终的期望——expect(widget.value, equals('Greater'));
正如我在调试器中看到的那样,onChanged 回调永远不会被调用,或者在输出中查找我的打印语句。
测试 DropdownButton 的行为有什么魔力?