我有一个问题,我有以下问题
Preferences.dart
/// Wrapper class for the shared preferences.
class Preferences {
Preferences({required SharedPreferences sharedPreferences})
: _sharedPreferences = sharedPreferences;
final SharedPreferences _sharedPreferences;
/// Writes the [value] to the shared preferences.
Future<bool> write({required String key, required String value}) =>
_sharedPreferences.setString(key, value);
/// Writes the list of [values] to the shared preferences.
Future<bool> writeList({required String key, required List<String> values}) =>
_sharedPreferences.setStringList(key, values);
/// Reads the value from the shared preferences.
String? read({required String key}) => _sharedPreferences.getString(key);
/// Reads the list of values from the shared preferences.
List<String>? readList({required String key}) =>
_sharedPreferences.getStringList(key);
/// Clears the shared preferences.
Future<bool> clearAll() => _sharedPreferences.clear();
/// Clears the shared preferences for the given [key].
Future<bool> clear({required String key}) => _sharedPreferences.remove(key);
}
在尝试创建相应的测试类时,我总是收到以下错误:
type 'Null' is not a subtype of type 'Future<bool>' test/mocks/mocks.dart 8:7 MockPreferences.write test/domain/preferences/preferences_test.dart 19:26 main.<fn>
目前这是我使用的测试类:
import 'package:flutter_test/flutter_test.dart';
import 'package:garrapata_app/domain/preferences/preferences.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mockito/mockito.dart';
import '../../mocks/mocks.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Preferences mockPreferences;
setUpAll(() async {
SharedPreferences.setMockInitialValues({'demo': 'demo'});
mockPreferences = MockPreferences();
});
test('demo', () {
when(mockPreferences.write(key: 'demo', value: 'demo')).thenAnswer((_) async => true);
expect(mockPreferences.write(key: 'demo', value: 'demo'), completion(true));
});
}
我不确定为什么一直为空,模拟值的初始化已解决并且分配已完成。
你没有等到
SharedPreferences
set 方法得到完整的结果
Future<bool> write({required String key, required String value}) =>
_sharedPreferences.setString(key, value);
Future<bool> write({required String key, required String value}) =>
await _sharedPreferences.setString(key, value);
await
对于set方法,任何SharedPreferences
set方法都需要等待。
希望对您有帮助。