When writing testing code for use cases in Flutter, it is essential to test failure cases. Testing failure cases ensures that your application handles errors gracefully and provides the correct responses or actions when something goes wrong.
Here's a brief guide on how to test failure cases in Flutter.
class FetchUserProfile {
final UserRepository repository;
FetchUserProfile(this.repository);
Future<Either<Failure, UserProfile>> execute(String userId) async {
try {
final userProfile = await repository.getUserProfile(userId);
return Right(userProfile);
} catch (e) {
return Left(ServerFailure());
}
}
}
abstract class UserRepository {
Future
getUserProfile(String userId); }
class UserProfile {
final String id;
final String name;
final String email;
UserProfile({required this.id, required this.name, required this.email});
}
class Failure {}
class ServerFailure extends Failure {}
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:dartz/dartz.dart';
class MockUserRepository extends Mock implements UserRepository {}
void main() {
late FetchUserProfile useCase;
late MockUserRepository mockUserRepository;
setUp(() {
mockUserRepository = MockUserRepository();
useCase = FetchUserProfile(mockUserRepository);
});
final tUserId = '123';
final tUserProfile = UserProfile(id: '123', name: 'John Doe', email: 'johndoe@example.com');
test('should return UserProfile when the call to repository is successful', () async {
// Arrange
when(mockUserRepository.getUserProfile(any)).thenAnswer((_) async => tUserProfile);
// Act
final result = await useCase.execute(tUserId);
// Assert
expect(result, Right(tUserProfile));
verify(mockUserRepository.getUserProfile(tUserId));
verifyNoMoreInteractions(mockUserRepository);
});
test('should return ServerFailure when the call to repository fails', () async {
// Arrange
when(mockUserRepository.getUserProfile(any)).thenThrow(ServerException());
// Act
final result = await useCase.execute(tUserId);
// Assert
expect(result, Left(ServerFailure()));
verify(mockUserRepository.getUserProfile(tUserId));
verifyNoMoreInteractions(mockUserRepository);
});
}