英文:
How to mock SharedPreferences.getInstance()?
问题
如何在Flutter测试中模拟SharedPreferences.getInstance()?
我在Google上搜索了一下,没有找到答案。
我还尝试了ChatGPT,并得到了以下答案:
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mocktail/mocktail.dart';
class MockSharedPreferences extends Mock implements SharedPreferences {}
void main() {
group(
'Login Tests',
() {
testWidgets('Login', (WidgetTester tester) async {
final mockSharedPreferences = MockSharedPreferences();
// Not working.
when(() => MockSharedPreferences.getInstance()).thenAnswer((_) => Future.value(mockSharedPreferences));
});
}
);
}
必须完全执行的lib中的登录函数:(它在SharedPreferences.getInstance()行卡住了,这就是为什么我想要模拟它的原因)
void login() {
if (
username.isNotEmpty
&& password.isNotEmpty
) {
dio.post(
'${Config.url}/api/users/login/',
data: {
'username': username,
'password': password
}
).then(
(Response<dynamic> response) async {
if (response.statusCode == 200) {
String token = response.data['key'];
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString('token', token);
BlocProvider.of<AccountBloc>(context).add(LoginEvent(token));
Future.delayed(
Duration.zero,
() async {
Navigator.of(context).popAndPushNamed('/');
}
);
} else {
throw 'Data: ${response.data}. Code: ${response.statusCode}. Message: ${response.statusMessage}';
}
}
).catchError(
(dynamic error) {
print('Login error: ${error}');
}
);
}
}
英文:
How to mock SharedPreferences.getInstance() in Flutter Test?
I have searched on Google and found no answers.
I also tried ChatGPT and came up with this:
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mocktail/mocktail.dart';
class MockSharedPreferences extends Mock implements SharedPreferences {}
void main() {
group(
'Login Tests',
() {
testWidgets('Login', (WidgetTester tester) async {
final mockSharedPreferences = MockSharedPreferences();
// Not working.
when(() => MockSharedPreferences.getInstance()).thenAnswer((_) => Future.value(mockSharedPreferences));
});
}
);
}
The login function in the lib that has to be executed fully: (It gets stuck at the SharedPreferences.getInstance() line, that's why I want to mock it)
void login() {
if (
username.isNotEmpty
&& password.isNotEmpty
) {
dio.post(
'${Config.url}/api/users/login/',
data: {
'username': username,
'password': password
}
).then(
(Response<dynamic> response) async {
if (response.statusCode == 200) {
String token = response.data['key'];
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setString('token', token);
BlocProvider.of<AccountBloc>(context).add(LoginEvent(token));
Future.delayed(
Duration.zero,
() async {
Navigator.of(context).popAndPushNamed('/');
}
);
} else {
throw 'Data: ${response.data}. Code: ${response.statusCode}. Message: ${response.statusMessage}';
}
}
).catchError(
(dynamic error) {
print('Login error: ${error}');
}
);
}
}
答案1
得分: 1
在测试中正确使用SharedPreferences的方法是使用setMockInitialValues()
方法,正如官方包文档所述:https://pub.dev/packages/shared_preferences。
此外,可以查看这个完整示例:https://blog.victoreronmosele.com/mocking-shared-preferences-flutter
示例代码:
test('Mock data in SharedPreferences', () async {
SharedPreferences.setMockInitialValues({'test': 1});
SharedPreferences sp = await SharedPreferences.getInstance();
expect(sp.getInt('test'), 1);
});
英文:
The right way to use SharedPreferences in tests is to use the setMockInitialValues()
method, as reported on the official package: https://pub.dev/packages/shared_preferences.
Also, look at this for a complete example: https://blog.victoreronmosele.com/mocking-shared-preferences-flutter
An example:
test('Mock data in SharedPreferences', () async {
SharedPreferences.setMockInitialValues({'test': 1});
SharedPreferences sp = await SharedPreferences.getInstance();
expect(sp.getInt('test'), 1);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论