我正在编写一个颤振应用程序,在编写测试时遇到了这个问题。该方法应该将数据写入TextFields并点击一个按钮将数据保存在SharedPrefs中:
testWidgets('Click on login saves the credentials',
(WidgetTester tester) async {
await tester.pumpWidget(MyApp());
await tester.enterText(find.byKey(Key('phoneInput')), 'test');
await tester.enterText(find.byKey(Key('passwordInput')), 'test');
await tester.tap(find.byIcon(Icons.lock));
SharedPreferences prefs = await SharedPreferences.getInstance();
expect(prefs.getString('phone'), 'test');
expect(prefs.getString('password'), 'test');
});此测试将无法获得包含此错误的SharedPreferences实例:
The following TimeoutException was thrown running a test:
TimeoutException after 0:00:03.500000: The test exceeded the timeout. It may have hung.
Consider using "addTime" to increase the timeout before expensive operations.Update:似乎问题不在于超时,因为即使有60秒的时间,测试也无法解决SharedPreferences实例。
发布于 2020-06-01 16:41:31
您可以使用提供的模拟setMockInitialValues。
testWidgets('Click on login saves the credentials',
(WidgetTester tester) async {
await tester.pumpWidget(MyApp());
SharedPreferences.setMockInitialValues(<String, dynamic>{
'flutter.phone': '',
'flutter.password': '',
});
await tester.enterText(find.byKey(Key('phoneInput')), 'test');
await tester.enterText(find.byKey(Key('passwordInput')), 'test');
await tester.tap(find.byIcon(Icons.lock));
SharedPreferences prefs = await SharedPreferences.getInstance();
expect(prefs.getString('phone'), 'test');
expect(prefs.getString('password'), 'test');
});发布于 2019-01-14 20:57:50
正如在github中提到的,您可以在测试开始时这样做:
tester.addTime(const Duration(seconds: 10));下面是链接和完整的示例:https://github.com/flutter/flutter/issues/19175
testWidgets('MyWidget', (WidgetTester tester) async {
final AutomatedTestWidgetsFlutterBinding binding = tester.binding;
binding.addTime(const Duration(seconds: 10)); // or longer if needed
await tester.pumpWidget(new MyWidget());
await tester.tap(find.text('Save'));
expect(find.text('Success'), findsOneWidget);
});发布于 2021-06-16 07:43:26
TruongSinh提供的解决方案不适合我。当我试图从代码(而不是测试)中将值设置为SharedPreferences时,我得到了错误。
这是对这个答案的补充。您需要自己重新实现setter:
import 'package:flutter/services.dart';
void main() {
setUpAll(() {
final values = <String, dynamic>{}; // set initial values here if desired
const MethodChannel('plugins.flutter.io/shared_preferences')
.setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return values;
} else if (methodCall.method.startsWith("set")) {
values[methodCall.arguments["key"]] = methodCall.arguments["value"];
return true;
}
return null;
});
});
testWidgets('Test if your code works as designed', (WidgetTester tester) async {
...
});
}https://stackoverflow.com/questions/54188939
复制相似问题