I am using MVP architecture for building my app. My presenter calls a DataManager which is responsible for getting data either from the network or a database. As I am using RxJava, I subscribe Observers in the Presenter and pass the appropriate state to UI. My service layer has the Android Context and it will also create an Exception of my own type which has a reference to the Context as well.
if (isNetworkConnected()) {
final Call<ServiceResponse<AppVersion>> call = mService.getAppVersion();
try {
final Response<ServiceResponse<AppVersion>> response = call.execute();
if (response.isSuccessful()) {
final ServiceResponse<AppVersion> serviceResponse = response.body(); response.body();
if (serviceResponse.isSuccess()) {
subscriber.onNext(serviceResponse.getData());
} else {
subscriber.onError(new CustomException(mContext, response.code(), response.message(), serviceResponse.getErrorList()));
}
} else {
subscriber.onError(new CustomException(mContext, response.code(), response.message(), response.errorBody().string()));
}
} catch (IOException e) {
e.printStackTrace();
subscriber.onError(e);
} finally {
subscriber.onCompleted();
}
} else {
subscriber.onError(new NoInternetException());
}
My CustomException also logs the crash in Crashlytics. When I am unit testing this code I am getting an exception from Crashlytics not being initialized. So I need to mock the static method logException
of Crashlytics. But how should I pass this mock object as presenter doesn't take this object?
public staticErrorType getErrorType(Throwable throwable) {
//409: Not handled as its a conflict response code and comes in PUT/POST
if (throwable instanceof IOException) {
return ErrorType.NO_INTERNET;
} else if (throwable instanceof CustomException) {
final int errorCode = ((CustomException) throwable).mErrorCode;
if (errorCode == 404) {
return ErrorType.NOT_FOUND;
} else if (errorCode == 401) {
return ErrorType.UNAUTORISED;
} else if (errorCode == 403) {
return ErrorType.FORBIDDEN;
} else if (errorCode == 500 || errorCode == 502) {
return ErrorType.NO_SERVER_TRY_AGAIN;
} else if (errorCode > 500 && errorCode < 599) {
return ErrorType.NO_SERVER_TRY_LATER;
} else if (errorCode == 1000) {
return ErrorType.NO_COURSE_ENROLLED;
} else if (errorCode == 1001) {
return ErrorType.NO_COURSE_STARTED;
}
}
if (throwable != null) {
Crashlytics.logException(throwable);
}
return ErrorType.SOME_THING_WENT_WRONG;
}