Android Studio 2.3 RC 1
I am using MVP architecture and want to run JVM unit tests.
In my model, I use Retrofit2 and RxJava to extract movies from the API. I want to check the getPopularMovies(...) function getPopularMovies(...) However, this function will call the web server. However, in the test I want to somehow mock it and just check the onSuccess() and onFailure() methods.
My model class looks like this snippet so that it is 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'm trying to solve is how can I use Mockito to test getPopularMovies without actually calling the network service? I just want to check this: popularMoviesResultsListener.onFailure(e.getMessage()) will be caused by the inability to receive movies as well as popularMovieResultsListener.onSuccess(results); will be called upon to succeed in receiving films
I have such a test, but I'm not sure if this is correct:
@Test public void shouldDisplaySuccessWhenNetworkSucceeds() { Results results = new Results(); MovieListModelContract.PopularMovieResultsListener mockPopularMoviesResultsListener = Mockito.mock(MovieListModelContract.PopularMovieResultsListener.class); MovieListModelImp movieListModelImp = new MovieListModelImp(); movieListModelImp.getPopularMovies(mockPopularMoviesResultsListener); verify(mockPopularMoviesResultsListener, times(1)).onSuccess(results); }
So my problem is, how can I make fun of a network request call and verify that the expected onSuccess () and onFailure () functions work correctly?
android rx-java mockito retrofit2
ant2009
source share