mercredi 24 février 2016

Verify mock interactions within anonymous inner class

I am trying to test my ViewModel in my application, here is the constructor:

@Inject
public SearchUserViewModel(@Named("searchUser") UseCase searchUserUseCase) {
  this.searchUserUseCase = searchUserUseCase;
}

In my test I create a SearchUserUseCase with mocks like this:

Observable error = Observable.error(new Throwable("Error"));
when(gitHubService.searchUser(MockFactory.TEST_USERNAME_ERROR)).thenReturn(error);

when(ObserverThread.getScheduler()).thenReturn(Schedulers.immediate());
when(SubscriberThread.getScheduler()).thenReturn(Schedulers.immediate());

searchUserUseCase = new SearchUserUseCase(gitHubService, SubscriberThread, ObserverThread);

In my ViewModel class I have this snippet which I want to test:

public void onClickSearch(View view) {
  loadUsers();
}

private void loadUsers() {
  if (username == null) {
    fragmentListener.showMessage("Enter a username");
  } else {
    showProgressIndicator(true);
    searchUserUseCase.execute(new SearchUserSubscriber(), username);
  }
}

private final class SearchUserSubscriber extends DefaultSubscriber<SearchResponse> {

  @Override
  public void onCompleted() {
    showProgressIndicator(false);
  }

  @Override
  public void onError(Throwable e) {
    showProgressIndicator(false);
    fragmentListener.showMessage("Error loading users");
  }

  @Override
  public void onNext(SearchResponse searchResponse) {
    List<User> users = searchResponse.getUsers();
    if (users.isEmpty()) {
      fragmentListener.showMessage("No users found");
    } else {
      fragmentListener.addUsers(users);
    }
  }

}

Finally in my test I have this:

@Test
public void shouldDisplayErrorMessageIfErrorWhenLoadingUsers() {
  SearchUserViewModel searchUserViewModel = new SearchUserViewModel(searchUserUseCase);
  searchUserViewModel.setFragmentListener(mockFragmentListener);
  searchUserViewModel.setUsername(MockFactory.TEST_USERNAME_ERROR);
  searchUserViewModel.onClickSearch(view);
  verify(mockFragmentListener).showMessage("Error loading users");
}

I get this error from Mockito:

Wanted but not invoked:
fragmentListener.showMessage(
  "Error loading users"
);

I am not sure if this is a good test, but I somehow want to test the SearchUserSubscriber one way or another. Thanks

Aucun commentaire:

Enregistrer un commentaire