“Null”类型不是 flutter 中“Future<bool>”类型的子类型

问题描述 投票:0回答:1
    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的待办事项应用程序编写测试,我刚刚添加了数据源的代码。还有其他测试,例如用于获取所有保存的待办事项的测试,它运行良好,我的问题在于这个测试

flutter dart debugging mockito sharedpreferences
1个回答
0
投票

尝试更换:

when(mockSharedPreferences
  .setString(prefKey, expectedJsonString))
  .thenAnswer((_) async => true);

when(mockSharedPreferences
  .setString(prefKey, expectedJsonString))
  .thenAnswer((_) async => Future.value(true));
© www.soinside.com 2019 - 2024. All rights reserved.