Android Studio 2.3 RC 1
I am using the MVP architecture and want to run JVM unit tests.
In my Model I am using Retrofit2 and RxJava to fetch movies from a API. I want to test the function getPopularMovies(...) However, this function will make a call to the webserver. However, in the test I want to mock this somehow and just test the onSuccess() and onFailure() methods are called.
My model class looks like this snippet only to keep it short:
public class MovieListModelImp implements MovieListModelContract {
@Override
public void getPopularMovies(PopularMovieResultsListener popularMovieResultsListener) {
mSubscription = mMovieAPIService.getPopular(Constants.MOVIES_API_KEY)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Results>() {
@Override
public void onCompleted() {
Timber.d("onCompleted");
}
@Override
public void onError(Throwable e) {
Timber.e(e, "onError");
popularMovieResultsListener.onFailure(e.getMessage());
}
@Override
public void onNext(Results results) {
Timber.d("onNext %d", results.getResults().size());
popularMovieResultsListener.onSuccess(results);
}
});
}
}
And the interface:
public interface MovieListModelContract {
interface PopularMovieResultsListener {
void onFailure(String errorMessage);
void onSuccess(Results popularMovies);
}
void getPopularMovies(PopularMovieResultsListener popularMovieResultsListener);
}
My problem I am trying to solve is how can I use Mockito to test the getPopularMovies without actually calling the network service? I just want to test that:
popularMoviesResultsListener.onFailure(e.getMessage()) will be called on failure to get movies
and
popularMovieResultsListener.onSuccess(results); will be called on success when movies are recieved
I have a test like this but I am not sure if this is correct:
@Test
public void shouldDisplaySuccessWhenNetworkSucceeds() {
/* Results is the movie results class that is returned */
Results results = new Results();
/* Mock the listener */
MovieListModelContract.PopularMovieResultsListener mockPopularMoviesResultsListener =
Mockito.mock(MovieListModelContract.PopularMovieResultsListener.class);
/* Real instance of the model */
MovieListModelImp movieListModelImp = new MovieListModelImp();
/* Call getPopularMovies with mock listener - However, this will still make a real network request */
movieListModelImp.getPopularMovies(mockPopularMoviesResultsListener);
/* Verify - but I think I have got this all wrong */
verify(mockPopularMoviesResultsListener, times(1)).onSuccess(results);
}
So my problem is how can I mock a call to a network request and test the expected onSuccess() and onFailure() is working correctly?