我创建了一种从web-service
接收一些数据的方法,我正在使用retrofit
,rx
,并且我正在使用juint
和mockito
来测试我的代码。我可以很好地测试此方法,但是在onCompleted
的rx
方法中,我正在调用另一种方法( savetodatabase )
如何将此依赖性分开?我不想在测试中调用此方法,请参阅下面的代码:
subscription = githubService.publicRepositories(username)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(application.defaultSubscribeScheduler())
.subscribe(new Subscriber<List<Repository>>()
{
@Override
public void onCompleted()
{
progressVisibility.set(View.INVISIBLE);
if (!repositories.isEmpty())
{
recyclerViewVisibility.set(View.VISIBLE);
}
else
{
infoMessage.set(context.getString(R.string.text_empty_repos));
infoMessageVisibility.set(View.VISIBLE);
}
//THIS METHOD SHOULD NOT BE CALLED IN MY TEST, I WANT TO VERIFY IT
saveToDatabase(MainViewModel.this.repositories);
}
@Override
public void onError(Throwable error)
{
Log.e(TAG, "Error loading GitHub repos ", error);
progressVisibility.set(View.INVISIBLE);
if (isHttp404(error))
{
infoMessage.set(context.getString(R.string.error_username_not_found));
}
else
{
infoMessage.set(context.getString(R.string.error_loading_repos));
}
infoMessageVisibility.set(View.VISIBLE);
}
@Override
public void onNext(List<Repository> repositories)
{
MainViewModel.this.repositories = repositories;
}
});
这是我的测试:
String username = "usernameWithRepos";
TextView textView = new TextView(application);
textView.setText(username);
List<Repository> mockRepos = MockModelFabric.newListOfRepositories(10);
doReturn(rx.Observable.just(mockRepos)).when(githubService).publicRepositories(username);
mainViewModel.onSearchAction(textView, EditorInfo.IME_ACTION_SEARCH, null);
verify(dataListener).onRepositoriesChanged(mockRepos);
assertEquals(mainViewModel.infoMessageVisibility.get(), View.INVISIBLE);
assertEquals(mainViewModel.progressVisibility.get(), View.INVISIBLE);
assertEquals(mainViewModel.recyclerViewVisibility.get(), View.VISIBLE);
您不能在测试中调用此方法。而是将您的类数据库依赖项添加并模拟它。例如:
//in your class
DataBaseClass databaseClass = new ...
...
dataBaseClass.save(...);
//in your test
@Mock DataBaseClass databaseClass;