简体   繁体   中英

Flutter secure storage unit test

Hey as a part of project I would like to test my classes like the one below but I have a little problem. Impossible for me to test, I always encounter the same errors "type 'Null' is not a subtype of type 'Future<OAuthToken?>'" or "Null check operator used on a null value". For example:

class Authentication {
  final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();

  static const String BEARER_TOKEN = 'BEARER_TOKEN';

 Future<OAuthToken> setToken(OAuthTokenResponse token) async {
  assert(token.accessToken != null, 'A non null token is required');
  final String jsonToken = json.encode(token.toJson());
  await _secureStorage.write(key: BEARER_TOKEN, value: jsonToken);
  return token;
 }

 Future< OAuthToken?> getToken() async {
  final String? jsonToken = await _secureStorage.read(key: BEARER_TOKEN);
  if (jsonToken == null) {
   return null;
  }
  return OAuthToken(json.decode(jsonToken));
 }

 Future<void> deleteToken() async {
  await _secureStorage.delete(key: BEARER_TOKEN);
 }
}

My Unit testing:

void main() {
 final Authentication dataSource = Authentication();
 final MockFlutterSecureStorage mockSecureStorage = MockFlutterSecureStorage();

 final token = OAuthToken.fromJson(json.decode(fixture('oauth_token_response.json')));

group('getToken', () {
 test('should return OAuthToken from FlutterSecureStorage when there is one the saved', () async {
   // arrange
   when(() => mockSecureStorage.read(key: BEARER_TOKEN)).thenAnswer((_) async => fixture('oauth_token_response.json'));

   // act
   final result = await dataSource.getToken();

   //assert
   verify(() => mockSecureStorage.read(key: BEARER_TOKEN));
   expect(result, equals(token));
 });

 test('should return null when is not saved token', () async {
   // arrange
   when(() => mockSecureStorage.read(key: BEARER_TOKEN)).thenAnswer((_) async => null);

   // act
   final result = await dataSource.getToken();

   //assert
   expect(result, equals(null));
 });
});

group('saveToken', () {
 test('should call FlutterSecureStorage to save token', () async {
   // arrange
   when(() => mockSecureStorage.write(key: BEARER_TOKEN, value: json.encode(token))).thenAnswer((invocation) => Future<void>.value());

   //act
   await dataSource.setToken(token);

   // assert
   final expectedJsonString = json.encode(token.toJson());
   verify(() => mockSecureStorage.write(key: BEARER_TOKEN, value: expectedJsonString));
 });
});
}

I tried Cocktail and Mockito and I have the same error... A problem with mock maybe?

Thanks

Add the option to pass the secure storage object to Authentication() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM