Image for post
Image for post
RxJava — “Seriously great” — Me 2015

RxJava: Unit Testing Examples

Nathan Hunston
Sep 11, 2015 · 3 min read

Setting the Scene

Testing, How?

Image for post
Image for post
@Test
public void testGetCountriesObservable_FiltersOutAtlantis() throws Exception {
List<String> inputCountries = new ArrayList<>();
inputCountries.add("USA");
inputCountries.add("China");
inputCountries.add("Atlantis");

List<String> expectedCountries = new ArrayList<>();
expectedCountries.add("USA");
expectedCountries.add("China");

ViewModel viewModel = new ViewModel(inputCountries);
TestSubscriber<String> testSubscriber = new TestSubscriber<>();

viewModel.getCountriesObservable().subscribe(testSubscriber);

testSubscriber.assertReceivedOnNext(expectedCountries);
}
return Observable.just(countries)
.doOnSubscribe(() -> isRequesting = true)
.flatMapIterable(countries -> countries)
.filter(country -> !country.equalsIgnoreCase("Atlantis"));
@Test
public void getCountriesObservable_StartsRequestWhenSubscribedTo() throws Exception {

ViewModel viewModel = new ViewModel(null);
TestSubscriber<String> testSubscriber = new TestSubscriber<>();

viewModel.getCountriesObservable().subscribe(testSubscriber);

assertTrue(viewModel.isRequesting());
}
return Observable.just(countries)
.doOnSubscribe(() -> isRequesting = true)
.doOnTerminate(() -> isRequesting = false)
.flatMapIterable(countries -> countries)
.filter(country -> !country.equalsIgnoreCase("Atlantis"));

Mobile Engineering

All things mobile

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store