I'm trying to use JUnit4 in an Android project, where I also use RxAndroid/RxJava.
What I do is calling REST API from UUID generator using retrofit
UUIDApi.java just an interface for retrofit calls (now is just one)
public interface UUIDApi {
static final String BASE_URL = "https://www.uuidgenerator.net";
@GET("/api/version4")
Observable<String> getUUID();
}
UUIDModel.java where retrofit is initialized and where the interface written above is implemented
public class UUIDModel implements UUIDApi{
private Retrofit retrofit;
private UUIDApi uuidApi;
UUIDObserver uuidObserver = new UUIDObserver();
public UUIDModel() {
retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(new ToStringConverterFactory())
.baseUrl(UUIDApi.BASE_URL)
.build();
uuidApi = retrofit.create(UUIDApi.class);
}
@Override
public Observable<String> getUUID() {
return uuidApi.getUUID();
}
public void generateUUID(){
Observable<String> observable = this.getUUID();
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(uuidObserver);
}
}
Than I have the UUIDObserver that is just a class that implements Observer.
Note: new ToStringConverterFactory is a class I found here
Executing this code using emulator, I know for sure that it works fine. The problem is that I don't understand how to junit this code since using rxAndroid/rxJava it gets executed in another thread.
I read that:
The official way to test an observable is by using a TestSubscriber, an helper subscriber provided directly by the RxJava library.
so I tried
@Test
public void test_uuid() throws Exception {
UUIDApi uuidApi = new UUIDModel();
Observable<String> observable = uuidApi.getUUID();
TestSubscriber<String> testSubscriber = new TestSubscriber<>();
observable.subscribe(testSubscriber);
}
but at observable.subscribe(testSubscriber);
I get the error 'cannot resolve method 'subscribe(io.reactivex.subscribers.TestSubscriber)'
What am I doing wrong? How should I cope with rxProgramming and JUnit?