I have this simple DataInteractor which fetches a JsonObject from an api. When the data is not null, I save it locally just in case next time the request fails I can load it from there. I want to create a unit test which checks that when the response is not empty I actually call the method which backs up the information (sharedPreferencesManager.setLocalBackup()).
I've done unit testing only once or twice and for much simpler cases. I've found this links but I honestly feel I'm missing something...well...cause I haven't been able to implement the test, basically.
Android test method called after presenter executes retrofit call
Unit Testing in Retrofit for Callback
My Interactor:
public class DataInteractorImpl implements MainActivityContract.DataInteractor {
private SharedPreferencesManager sharedPreferencesManager;
private Retrofit retrofit = new retrofit2.Retrofit.Builder()
.baseUrl("https://api.nytimes.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
public DataInteractorImpl(SharedPreferencesManager sharedPreferencesManager){
this.sharedPreferencesManager = sharedPreferencesManager;
}
@Override
public void getNoticeArrayList(final OnFinishedListener onFinishedListener) {
// RetrofitInstance interface
DataInteractorService dataService = retrofit.create(DataInteractorService.class);
Call<JsonObject> call = dataService.getNewsData(getCurrentDateYYYYMMDD());
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
// if the response is not null, try to process it. Otherwise check the local backup
if(response.body() != null){
sharedPreferencesManager.setLocalBackup(response.body().toString());
}
onFinishedListener.onFinished(response.body());
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
//check the local backup, return the backup if there is one
if(sharedPreferencesManager.getLocalBackup() != null) {
onFinishedListener.onFinished(sharedPreferencesManager.getLocalBackup());
} else {
onFinishedListener.onFailure(t);
}
}
});
}
private String getCurrentDateYYYYMMDD(){
Date date = new Date();
return new SimpleDateFormat("yyyyMMdd").format(date);
}
}
Any and help could be very useful. Thanks to all in advance!