在 flutter 中 mockito 上缺少存根错误。尝试在模拟的 SharedPreferences 上使用 setString

Missing stub error on mockito in flutter. Trying to use setString on mocked SharedPreferences

我正在尝试在我的 flutter 项目中使用 Mockito 模拟 sharedPreferences。这是错误日志。

package:mockito/src/mock.dart 190:7                                                                       Mock._noSuchMethod
package:mockito/src/mock.dart 184:45                                                                      Mock.noSuchMethod
test\feature\number_trivia\data\datasource\number_trivia_local_datasource_test.mocks.dart 67:14           MockSharedPreferences.setString
package:clean_arch_tdd/features/number_trivia/data/datasources/number_trivia_local_datasource.dart 31:30  NumberTriviaLocalDataSourceImpl.cacheLastNumberTrivia
test\feature\number_trivia\data\datasource\number_trivia_local_datasource_test.dart 51:18                 main.<fn>.<fn>

MissingStubError: 'setString'
No stub was found which matches the arguments of this method call:
setString('CACHED_NUMBER_TRIVIA', '{"text":"Test trivia","number":1}')

Add a stub for this method using Mockito's 'when' API, or generate the mock for MockSharedPreferences with 'returnNullOnMissingStub: true'.

错误是指这行代码。

local_data_source_test.dart

test('should call sharedPreferences to cache the data', () {
      dataSource.cacheLastNumberTrivia(tNumberTriviaModel);
      final expectedJsonString = jsonEncode(tNumberTriviaModel.toJson());
      verify(mockSharedPreferences.setString(
          cachedNumberTrivia, expectedJsonString));
    });

local_data_source.dart

@override
  Future<void> cacheLastNumberTrivia(NumberTriviaModel triviaToCache) {
    return sharedPreferences.setString(
        cachedNumberTrivia, jsonEncode(triviaToCache.toJson()));
  }

它表明缺少模拟的 sharedPreferences 中的方法 setString。我已经 运行 pub 命令来生成模拟。我在文件中也有一些使用 getString 方法的测试用例。而且效果很好。

是不是我遗漏了什么,所以无法使用 setString 方法?或者有解决这个问题的方法吗?

提前致谢。

其实我已经弄明白了,很抱歉没有立即发布答案。

我发现自己忘了调用 setString 方法的存根。这是代码。

group('cacheNumberTrivia', () {
    const tNumberTriviaModel =
        NumberTriviaModel(number: 1, text: 'Test trivia');

    test('should call sharedPreferences to cache the data', () async {
      when(mockSharedPreferences.setString(any, any))
          .thenAnswer((_) async => true);
      dataSource.cacheLastNumberTrivia(tNumberTriviaModel);
      final expectedJsonString = jsonEncode(tNumberTriviaModel.toJson());
      verify(mockSharedPreferences.setString(
          cachedNumberTrivia, expectedJsonString));
    });
  });

存根实际上是这一行:

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

我在用verify验证结果之前忘记调用when方法,因此抛出错误。