Unit Test - Verify Observable is subscribed

前端 未结 4 2098
攒了一身酷
攒了一身酷 2021-02-08 00:19

I have got the java code like this

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

and I want to verify the follow

4条回答
  •  独厮守ぢ
    2021-02-08 00:57

    Maybe you could use Observable.onSubscribe method together with RunTestOnContext rule? The TestContext can provide you with an Async object, that terminates the test only once it is completed. I think, that if you combine this with Observable#doOnSubscribe you can achieve the desired behavior.

    However, using Async might be a bit confusing sometimes. In the example below, if the observable is never subscribed onto, the doOnSubscribe function would never get evaluated and your test would not terminate.

    Example:

    @RunWith(VertxUnitRunner.class)
    public class SubscriptionTest {
    
      @Rule
      public RunTestOnContext vertxRule = new RunTestOnContext();
    
      @Test
      public void observableMustBeSubscribed(final TestContext context) {
        final Async async = context.async();
        final Observable observable = Observable.just("hello").doOnSubscribe(async::complete);
        final Manager mock = mock(Manager.class);
        when(mock.getObservable()).thenReturn(observable);
    
        mock.getObservable().subscribe();
      }
    
      interface Manager {
        Observable getObservable();
      }
    }
    

提交回复
热议问题