|
| 1 | +import 'package:common/core/result_type.dart'; |
| 2 | +import 'package:data/preferences/preferences.dart'; |
| 3 | +import 'package:data/repositories/auth_repository_impl.dart'; |
| 4 | +import 'package:mocktail/mocktail.dart'; |
| 5 | +import 'package:test/test.dart'; |
| 6 | + |
| 7 | +class MockPreferences extends Mock implements Preferences {} |
| 8 | + |
| 9 | +void main() { |
| 10 | + late AuthRepositoryImpl repository; |
| 11 | + late MockPreferences mockPreferences; |
| 12 | + |
| 13 | + setUp(() { |
| 14 | + mockPreferences = MockPreferences(); |
| 15 | + repository = AuthRepositoryImpl(mockPreferences); |
| 16 | + }); |
| 17 | + |
| 18 | + group('isLoggedIn', () { |
| 19 | + test('should return true when token exists', () { |
| 20 | + // Arrange |
| 21 | + when(() => mockPreferences.getToken()).thenReturn('some-token'); |
| 22 | + |
| 23 | + // Act |
| 24 | + final result = repository.isLoggedIn(); |
| 25 | + |
| 26 | + // Assert |
| 27 | + expect(result, true); |
| 28 | + verify(() => mockPreferences.getToken()).called(1); |
| 29 | + }); |
| 30 | + |
| 31 | + test('should return false when token is null', () { |
| 32 | + // Arrange |
| 33 | + when(() => mockPreferences.getToken()).thenReturn(null); |
| 34 | + |
| 35 | + // Act |
| 36 | + final result = repository.isLoggedIn(); |
| 37 | + |
| 38 | + // Assert |
| 39 | + expect(result, false); |
| 40 | + verify(() => mockPreferences.getToken()).called(1); |
| 41 | + }); |
| 42 | + }); |
| 43 | + |
| 44 | + group('login', () { |
| 45 | + test('should return success and set token when login is successful', |
| 46 | + () async { |
| 47 | + // Arrange |
| 48 | + const username = 'test_user'; |
| 49 | + const password = 'test_password'; |
| 50 | + when(() => mockPreferences.setToken(any())).thenAnswer((_) async {}); |
| 51 | + |
| 52 | + // Act |
| 53 | + final result = await repository.login(username, password); |
| 54 | + |
| 55 | + // Assert |
| 56 | + expect(result, isA<TSuccess>()); |
| 57 | + verify(() => mockPreferences.setToken('new-token')).called(1); |
| 58 | + }); |
| 59 | + }); |
| 60 | + |
| 61 | + group('logout', () { |
| 62 | + test('should clear token when logging out', () async { |
| 63 | + // Arrange |
| 64 | + when(() => mockPreferences.setToken(null)).thenAnswer((_) async {}); |
| 65 | + |
| 66 | + // Act |
| 67 | + await repository.logout(); |
| 68 | + |
| 69 | + // Assert |
| 70 | + verify(() => mockPreferences.setToken(null)).called(1); |
| 71 | + }); |
| 72 | + }); |
| 73 | +} |
0 commit comments