我有这个简单的DataInteractor,它可以从api中获取JsonObject。当数据不为null时,我将其保存在本地,以防万一下次请求失败时,可以从那里加载它。我想创建一个单元测试,以检查当响应不为空时我是否实际调用了备份信息的方法(sharedPreferencesManager.setLocalBackup())。
对于简单得多的情况,我只进行了一次或两次单元测试。我已经找到了此链接,但老实说,我觉得我缺少一些东西……嗯……因为我基本上无法实施该测试。
Android test method called after presenter executes retrofit call
Unit Testing in Retrofit for Callback
我的交互者:
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);
}
}
任何帮助都可能非常有用。 预先感谢所有人!