Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test - Verify Observable is subscribed

I have got the java code like this

 mDataManager.getObservable("hello").subscribe( subscriber );

and I want to verify the following Observable is being .subscribe()

I have tried to mock getObservable() and verify

 Observable<Response> res = mock(Observable.class);
 when(mDataManager.getObservable("hello")).thenReturn(res);
 verify(res).subscribe();

But there is an error

Caused by: java.lang.IllegalStateException: onSubscribe function can not be null.
at rx.Observable.subscribe(Observable.java:8167)
at rx.Observable.subscribe(Observable.java:8158)
at rx.Observable.subscribe(Observable.java:7962)
....
Caused by: rx.exceptions.OnErrorThrowable$OnNextValue: OnError while emitting onNext value: omni.neo.hk.omniapiservice.v4.model.external.UserLoginBean.class
at rx.exceptions.OnErrorThrowable.addValueAsLastCause(OnErrorThrowable.java:109)
at rx.exceptions.Exceptions.throwOrReport(Exceptions.java:187)
at rx.internal.operators.OperatorDoOnEach$1.onNext(OperatorDoOnEach.java:82)
... 48 more

I think it is not possible mock an Observable here, but without an mocked Observable I cannot doverify(res).subscribe()

Any suggestion in this case?

like image 392
Kone Man Avatar asked Nov 09 '16 04:11

Kone Man


1 Answers

I found that RxJava provides a class called TestSubject

You can create it like this

private TestScheduler eventsScheduler = new TestScheduler();
private TestSubject<MyEvent> eventObservable = TestSubject.create(eventsScheduler);

This will provide you with the method hasObservers() which returns a boolean.

@Test
public void testSubscription(){
    myTestClass.init(eventObservable);

    assertTrue(eventObservable.hasObservers());
}

Also the TestSubject allows you to perfectly time when events should be sent.

eventObservable.onNext(new MyEvent());
eventsScheduler.triggerActions(); 
like image 182
JDurstberger Avatar answered Sep 19 '22 15:09

JDurstberger