如何为单元测试选择合适的调度程序

时间:2016-08-24 13:05:22

标签: android unit-testing mockito junit4 rx-java

我有以下代码要测试:

public class MyInteractor implements Interactor<String, Boolean> {

  private MyRepository repository;

  @Inject
  public MyInteractor(MyRepository repository) {
      this.repository = repository;
  }

  @Override
  public Observable<Boolean> createObservable(final String s) {
      return Observable.create(new Observable.OnSubscribe<Boolean>() {
          @Override
          public void call(Subscriber<? super Boolean> subscriber) {

              Boolean response = repository.call(s);

              subscriber.onNext(response);
              subscriber.onCompleted();
          }
      })
              .subscribeOn(Schedulers.io());
   }
}

我写了以下单元测试:

@RunWith(MockitoJUnitRunner.class)
public class MyInteractorTest {

  @Mock
  MyRepository repository;

  @InjectMocks
  MyInteractor interactor;

  @Before
  public void init() {
      when(repository.call(any(String.class)))
              .thenReturn(true);
  }

  @Test
  public void myTest() throws Exception {

      Observable<Boolean> interactorObservable =
              interactor.createObservable("hello");
      TestSubscriber<Boolean> subscriber = TestSubscriber.create();

      interactorObservable.subscribe(subscriber);

      subscriber.assertNoErrors();

      subscriber.assertCompleted();
      subscriber.assertReceivedOnNext(singletonList(true));
  }
}

当我运行单元测试时,subscriber.assertCompleted()失败。但是,如果我删除subscribeOn(Schedulers.io())中的MyInteractor.createObservable(),一切正常。

有没有办法让测试运行完成而不是删除行subscribeOn(Schedulers.io())

1 个答案:

答案 0 :(得分:1)

这是因为myTest没有意识到在另一个线程上运行的东西,所以它会在Observable返回之前继续运行断言。

使用RxJavaHooks检测IO Scheduler在单元测试中返回Immediate Scheduler。

例如:RxJavaHooks.setOnIOScheduler(scheduler -> Schedulers.immediate())