我想在Android演示者上测试一个有回调函数的函数。这是功能:
public void findRandomUsers() {
view.showProgress();
mDataManager.getRandomUsers(USERS_SEARCH_NUMBER, new Callback<UserList>() {
@Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(view == null) return;
view.hideProgress();
if(response.body().getUsers().isEmpty()){
view.showIsEmptyError();
}
users = response.body();
users.setUsers(CheckRemovedUsers.avoidRemoveds(users.getUsers(), removedUsers.getRemovedUsers()));
users.setUsers(CheckDuplicatedUsers.removeDuplicated(users.getUsers()));
if(isFirstTime)
view.showUsersList(users);
else
view.updateUserList(users);
}
@Override
public void onFailure(Call<UserList> call, Throwable throwable) {
if(view == null) return;
view.hideProgress();
view.showError(throwable.getMessage());
}
});
}
Callback是一个retrofit2.Callback对象USERS_SEARCH_NUMBER是一个int对象。如果有可能我想控制回调响应控制的内容,如果它返回空响应或失败则显示正确的答案。
答案 0 :(得分:0)
你必须设计你的建筑,你有足够的接缝。
目前,您无法模仿Callback<UserList>
。为什么你没有
一个Factory
类,它为您提供回调?然后你可以轻松存根组件。
class UserListCallbackFactory {
public UserListCallbackFactory() {}
public Callback<UserList> getCallback(Presenter presenter) {
return new Callback<UserList>() {
@Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
presenter.onSuccess(response.body().getUsers());
}
@Override
public void onFailure(Call<UserList> call, Throwable throwable) {
presenter.onFailure(throwable);
}
}
}
}
现在,在演示者的构造函数中:
class Presenter extends ... {
Callback<UserList> userListCallback;
DataManager dataManager;
public Presenter(View view, UserListCallbackFactory factory, DataManager dataManager) {
...
userListCallback = factory.getCallback(this, view);
this.dataManager = dataManager;
...
}
public void onSuccess(List<User>) {
...
}
public void onFailure(Throwable e) {
...
}
}
现在你有足够的接缝来模拟单元测试类中的回调。
@RunWith(MockitoJUnitRunner.class)
public class PresenterTest {
...
@Mock View view;
@Mock Callback<UserList> userListCallback;
@Mock UserListCallbackFactory factory;
@Mock DataManager dataManager;
@InjectMocks
Presenter presenter;
...
@Test
public void succesfulResponse() {
when(factory.getCallback(presenter)).thenReturn(userListCallback);
when(dataManager.getRandomUsers(USERS_SEARCH_NUMBER, userListCallback))
.thenAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
userListCallback.onSuccess(SOME_LIST);
return null;
}
});
// check that appropriate actions are performed upon successful callback
}
}