group('localTodos', () {
final List<TodoModel> todos = [
const TodoModel(id: 1, title: "Test Todo 1", completed: false, userId: 1),
const TodoModel(id: 2, title: "Test Todo 2", completed: true, userId: 1),
];
test('should call SharedPreferences to save the data', () async {
final expectedJsonString = json.encode(todos.map((todo) => todo.toJson()).toList());
print('Test setup complete');
when(mockSharedPreferences.setString(prefKey, expectedJsonString)).thenAnswer((_) async => true);
await localDataSource.localTodos(todos);
print('After localTodos method call');
// Ensure we verify setString was called once
verify(mockSharedPreferences.setString(prefKey, expectedJsonString)).called(1);
});
});
@override
Future<List<TodoModel>> getLocalTodos() async {
final jsonString = sharedPreferences.getString('SAVED_TODOS');
if (jsonString != null) {
List decodedJson = json.decode(jsonString);
return decodedJson.map<TodoModel>((json) => TodoModel.fromJson(json)).toList();
} else {
throw Exception('No saved todos found');
}
}
@override
Future<void> localTodos(List<TodoModel> todos) async {
final List<Map<String, dynamic>> todoList = todos.map((todo) => todo.toJson()).toList();
await sharedPreferences.setString('SAVED_TODOS', json.encode(todoList));
}
正在为带有sharedpref的待办事项应用程序编写测试,我刚刚添加了数据源的代码。还有其他测试,例如用于获取所有保存的待办事项的测试,它运行良好,我的问题在于这个测试
尝试更换:
when(mockSharedPreferences
.setString(prefKey, expectedJsonString))
.thenAnswer((_) async => true);
由
when(mockSharedPreferences
.setString(prefKey, expectedJsonString))
.thenAnswer((_) async => Future.value(true));