Flutter unit test: type 'Null' is not a subtype of type 'T' in type cast - flutter

I tried to run unit test but i found an issue like below:
type 'Null' is not a subtype of type 'LoginResponse' in type cast
dart:async new Future.value
test/mock_utils.mocks.dart 259:22 MockBaseRepository.call
package:swap_recycling/features/auth/data/repository/login/login_repository_impl.dart 33:42 LoginRepositoryImpl.login
test/features/auth/data/repository/login/login_repository_impl_test.dart 30:38
and these my codes:
test.dart
void main() {
late MockLoginApiService _mockLoginApiService;
late MockSecureStorage _mockSecureStorage;
late MockBaseRepository _mockBaseRepository;
setUp(() {
_mockLoginApiService = MockLoginApiService();
_mockSecureStorage = MockSecureStorage();
_mockBaseRepository = MockBaseRepository();
});
test('Given LoginRepository When login Then return loginResponseSuccess',
() async {
final _repository = LoginRepositoryImpl(
_mockLoginApiService,
_mockSecureStorage,
_mockBaseRepository,
);
final result = await _repository.login(loginRequest);
expect(result, loginResponseSuccess);
verify(_mockLoginApiService.login(loginRequest)).called(1);
});
Login_repository.dart
final loginRepositoryProvider = Provider<LoginRepository>((ref) {
final loginApiService = ref.watch(provideLoginApiService);
final secureStorage = ref.watch(secureStorageProvider);
final baseRepository = ref.watch(baseRepositoryProvider);
return LoginRepositoryImpl(loginApiService, secureStorage, baseRepository);
});
class LoginRepositoryImpl extends LoginRepository {
final LoginApiService _loginApiService;
final SecureStorage _secureStorage;
final BaseRepository _baseRepository;
LoginRepositoryImpl(
this._loginApiService,
this._secureStorage,
this._baseRepository,
);
#override
Future<LoginResponse> login(LoginRequest request) async {
final result = await _baseRepository.call<LoginResponse>(
() => _loginApiService.login(request),
);
return result;
}
base_repository.dart
final baseRepositoryProvider = Provider<BaseRepository>((ref) {
return BaseRepository();
});
class BaseRepository {
Future<T> call<T>(FutureOr<T> Function() call) async {
try {
return await call();
} on DioError catch (e) {
if (e.error is SocketException) {
throw Failure(message: e.message);
}
if (e.response?.statusCode == serverErrorCode) {
throw Failure(
message: 'Server has some issue, please try again',
code: e.response?.statusCode,
);
}
throw Failure(
message: e.response?.statusMessage ?? 'Something went wrong',
code: e.response?.statusCode,
exception: e,
);
}
}
}
I tried to create a reuse function to return HTTP calls or handle errors.
I set generic type and send LoginResponse to tell BaseRepository that I want to return LoginResponse.
I can run it on an emulator but it doesn't work in a unit test.
Why It returns Null type?
I used mockito to generate mock class
mocks.dart
#GenerateNiceMocks([
//Repository
MockSpec<LoginRepository>(),
MockSpec<SettingRepository>(),
//Service
MockSpec<LoginApiService>(),
MockSpec<SecureStorage>(),
//Base
MockSpec<BaseRepository>(),
MockSpec<LoginRepositoryImpl>(),
])

Related

The argument type 'List<HospitalListModel>?' can't be assigned to the parameter type 'HospitalListModel'

i have bloc class and it throw an error with a message The argument type 'List<HospitalListModel>?' can't be assigned to the parameter type 'HospitalListModel'.
this is the bloc class:
class HospitalListBloc extends Bloc<HospitalListEvent, HospitalListState> {
HospitalListBloc() : super(HospitalListInitial()) {
final ApiRepository _apiRepository = ApiRepository();
on<GetCovidList>((event, emit) async {
try {
emit(HospitalListLoading());
final mList = await _apiRepository.fetchHospitalList();
emit(HospitalListLoaded(mList));
} on NetworkError {
emit(HospitalListError("Failed to fetch data. is your device online?"));
}
});
}
}
and the error is on emit(HospitalListLoaded(mList));, and in case if you want to know the API provider:
class ApiProvider {
final Dio _dio = Dio();
final String _url = 'http://lovemonster.my.id/hospital';
Future<List<HospitalListModel>?> fetchHospitalList() async {
try {
Response response = await _dio.get(_url);
return hospitalListModelFromJson(response.data);
} catch (error, stacktrace) {
print("Exception occurred: $error stackTrace: $stacktrace");
return Future.error("");
}
}
}
your HospitalListLoaded function should be
HospitalListLoaded(List<HospitalListModel> mList)
The argument type 'List<HospitalListModel>?' can't be assigned to the parameter type 'HospitalListModel'.
Your HospitalListLoaded function is declared as this:
void HospitalListLoaded(HospitalListModel model){
....
}
Here the parameter type is a single HospitalListModel, not a list of them. So, you can either pass a single HospitalListModel or you can change the parameter type to List<HospitalListModel>. In that case, you must change your logic inside that function.
Plus, notice the ? null operator. If the List you pass can be null, then the parameter type must be nullable. In that case,
void HospitalListLoaded(List<HospitalListModel>? models){
....
}
You are returning an Object of HospitalListModel but your Bloc class having method which accept list of HospitalListModel
You need to return list not an object
Check below code which will be useful
class ApiProvider {
final Dio _dio = Dio();
final String _url = 'http://lovemonster.my.id/hospital';
Future<List<HospitalListModel>?> fetchHospitalList() async {
try {
List<HospitalListModel> hospitalList = [];
Response response = await _dio.get(_url);
var mData = responseData.data as List;
hospitalList = mData.
.map<HospitalListModel?>((e) => hospitalListModelFromJson(e)
.toList();
return hospitalList;//return List not object
} catch (error, stacktrace) {
print("Exception occurred: $error stackTrace: $stacktrace");
return Future.error("");
}
}
}

how to mock the state of a StateNotifierProvider flutter

my test is throwing an exception because there is a StateNotifierProvider inside which is not overridden. for a regular Provider, i can override it using providerContainer, but for the state of a stateNotifierProvider, I don't know how to do it. I tried my best but I reached the limit of my best. I already saw this and this but it didn't help.
Appreciate much if someone could help me out of this. Thanks
My service File
class ReportService {
final Ref ref;
ReportService({
required this.ref,
});
Future<void> testReport() async {
//* How can i override this provider ?
final connection = ref.read(connectivityServiceProvider);
if (connection) {
try {
await ref.read(reportRepositoryProvider).testFunction();
} on FirebaseException catch (e, st) {
ref.read(errorLoggerProvider).logError(e, st);
throw Exception(e.message);
}
} else {
throw Exception('Check internet connection...');
}
}
}
final reportServiceProvider = Provider<ReportService>((ref) => ReportService(
ref: ref,
));
My test file
void main() {
WidgetsFlutterBinding.ensureInitialized();
final reportRepository = MockReportRepository();
ReportService makeReportService() {
final container = ProviderContainer(overrides: [
reportRepositoryProvider.overrideWithValue(reportRepository),
]);
addTearDown(container.dispose);
return container.read(reportServiceProvider);
}
test('test test', () async {
//How to stub the connectivityServiceProvider here ?
when(reportRepository.testFunction)
.thenAnswer((invocation) => Future.value());
final service = makeReportService();
await service.testReport();
verify(reportRepository.testFunction).called(1);
});
My StateNotifierProvider
class ConnectivityService extends StateNotifier<bool> {
ConnectivityService() : super(false);
}
final connectivityServiceProvider =
StateNotifierProvider<ConnectivityService, bool>(
(ref) => ConnectivityService());

Mocking AWS Amplify in Flutter unit tests

I have a UserRepository class and pass it an Amplify Auth Session object upon being instantiated, which it then stores for later use.
I'm trying to mock this out in my unit tests using Mockito and Mocktail. I've followed their guides on mocking (in this case a future), however I get this error:
_TypeError (type 'Null' is not a subtype of type 'Future<AuthSession>')
I'm not sure what I'm doing wrong, it seems as though my mock and test are correct but the UserRepository isn't using the mock.
Here is my class:
class UserRepository extends ChangeNotifier {
AuthCategory auth;
....
UserRepository({required this.auth}) {
fetchAuthSession();
}
...
void fetchAuthSession() async {
try {
final result = await auth.fetchAuthSession( // <--- Error points here
options: CognitoSessionOptions(getAWSCredentials: true),
);
sub = (result as CognitoAuthSession).userSub!;
token = result.userPoolTokens!.idToken;
await fetchUserData();
notifyListeners();
} on AuthException catch (e) {
print(e.message);
}
}
...
}
Here are my test an mock:
test("Set isAuthenticated to true", () {
MockAuth auth = MockAuth();
when(auth.fetchAuthSession).thenAnswer((_) async {
return Future(
() => MockAuthSession(),
);
});
final user = UserRepository(auth: auth);
expect(user.isAuthenticated, false);
user.setAuthenticatedStatus(true);
expect(user.isAuthenticated, true);
});

Mokito wont return a stubbed value

I started TDD recently and it has slowed my progress, I m trying to stub a return value with Mockito, but i keep getting "null is not a subtype of Future-dynamic' not sure what i did wrong, here is my setup
class ImageSelectorMock extends Mock implements ImageSelector {}
getImageSelectorMock({logo}) {
_unregisterIfRegistered<ImageSelector>();
var imageSelector = ImageSelectorMock();
if (logo != null) {
when(imageSelector.businessLogo).thenReturn('string');
when(imageSelector.uploadImage(null, 'folder'))
.thenAnswer((realInvocation) async =>
Future.value('send this')
);
}
locator.registerSingleton<ImageSelector>(imageSelector);
return imageSelector;
}
setupService() {
//getAuthServiceMock();
//getFirestoreServiceMock();
//getNavigationServiceMock();
getImageSelectorMock();
}
void _unregisterIfRegistered<T extends Object>() {
if (locator.isRegistered<T>()) {
locator.unregister<T>();
}
}
getImageSelectorMock takes an optional arg "logo" to check if imageSelector.uploadImage is called. Also, I'm using a locator/get_it package
group('RegistrationviewmodelTest -', () {
setUp(() => {setupService()});
test('when business logo is NOT null => uplaodImage should be called', () async {
// final navigation = getNavigationServiceMock();
// final fireStore = getFirestoreServiceMock();
final imageSelector = await getImageSelectorMock(logo: "test");
final model = RegistraionViewModel();
await model.createBusiness({
'title': "text",
'description': "text",
});
verify(imageSelector.uploadImage('', 'upload'));
// verify(navigation.navigateTo());
});
});
// uploadImage does
Future uploadImage(file, folder) async {
// String fileName = basename(_imageFile.path);
String fileName = basename(file.path);
final firebaseStorageRef =
FirebaseStorage.instance.ref().child('$folder/$fileName');
final uploadTask = firebaseStorageRef.putFile(file);
final taskSnapshot = await uploadTask;
return taskSnapshot.ref.getDownloadURL().then((value) => value);
}
uploadImage is just an image picker that returns download Url from fire storege.
Thanks for helping out!!

dartz: exception in function is not caught in attempt

I am using dartz with flutter. I want to use Either type with all API calls as suggested in this article
Below is the way I have wrapped API to Task
Future<Either<ApiException, SendOtpDto>> receiveOtp(
String phoneNumber) async {
return Task<SendOtpDto>(() async {
final String url = 'AuthenticationApi/sendOtp/$phoneNumber';
final Map<String, dynamic> response = await apiWrapper.get(url);
final SendOtpDto dto = SendOtpDto.fromJson(response);
if (!dto.success) {
throw ServerErrorException(dto.error); //Exception is thrown here
}
return dto;
}).attempt().mapLeftToFailure().run();
}
I expect attempt() should catch all throw as ApiException. Currently it gives error type 'Future<Either<ApiException, dynamic>>' is not a subtype of type 'FutureOr<Either<ApiException,
SendOtpDto>>
Below is how I am using the Api
if (event is GetOtpButtonPressed) {
yield LoginApiLoading();
final Either<ApiException, SendOtpDto> result = await apiManager.authentication(context).receiveOtp(event.username);
yield result.fold<LoginState>(
(ApiException exception) { return LoginFailure(error: exception.toString()); },
(SendOtpDto dto) { return LoginOtpSent(dto: dto); });
}