如何在RxJava中使用TestScheduler

时间:2014-11-02 12:11:49

标签: rx-java

我应该如何使用RxJava的TestScheduler?我来自.NET背景,但RxJava中的TestScheduler似乎与.NET rx中的测试调度程序的工作方式不同。

以下是我要测试的示例代码

Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS);
contactsRepository.find(index)
  .buffer(MAX_CONTACTS_FETCH)
  .zipWith(tick, new Func2<List<ContactDto>, Long, List<ContactDto>>() {
    @Override
    public List<ContactDto> call(List<ContactDto> contactList, Long aLong) {
      return contactList;
    }
  }).subscribe()

我试过了:

subscribeOn(testScheduler)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS);
testScheduler.triggerActions();

没有运气。

2 个答案:

答案 0 :(得分:22)

我举了一个如何使用TestScheduler的例子。我认为它与.NET实现非常相似

@Test
public void should_test_the_test_schedulers() {
    TestScheduler scheduler = new TestScheduler();
    final List<Long> result = new ArrayList<>();
    Observable.interval(1, TimeUnit.SECONDS, scheduler).take(5).subscribe(result::add);
    assertTrue(result.isEmpty());
    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);
    assertEquals(2, result.size());
    scheduler.advanceTimeBy(10, TimeUnit.SECONDS);
    assertEquals(5, result.size());
}

https://github.com/bric3/demo-rxjava-humantalk/blob/master/src/test/java/demo/humantalk/rxjava/SchedulersTest.java

修改 根据您的代码:您应该将调度程序传递给Observable.interval操作,因为这是您要控制的:

    TestScheduler scheduler = new TestScheduler();

    Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler);
    Subscription toBeTested = Observable.from(Arrays.asList(1, 2, 3, 4, 5))
            .buffer(3)
            .zipWith(tick, (i, t) -> i)
            .subscribe(System.out::println);

    scheduler.advanceTimeBy(2, TimeUnit.SECONDS);

答案 1 :(得分:12)

你有一些课程:

public class SomeClass {
  public void someMethod() {
    Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS);
    contactsRepository.find(index)
      .buffer(MAX_CONTACTS_FETCH)
      .zipWith(tick, new Func2<List<ContactDto>, Long, List<ContactDto>>() {
        @Override
        public List<ContactDto> call(List<ContactDto> contactList, Long aLong) {
          return contactList;
        }
      }).subscribe()
  }
}

在文档中查找[Observable.interval][1],您将看到它在计算调度程序上运行,因此我们在测试中覆盖它。

public class SomeClassTest {
  private TestScheduler testScheduler;

  @Before
  public void before() {
    testScheduler = new TestScheduler();
    // set calls to Schedulers.computation() to use our test scheduler
    RxJavaPlugins.setComputationSchedulerHandler(ignore -> testScheduler);
  }

  @After
  public void after() {
    // reset it
    RxJavaPlugins.setComputationSchedulerHandler(null);
  }

  @Test
  public void test() {
    SomeClass someInstance = new SomeClass();
    someInstance.someMethod();

    // advance time manually
    testScheduler.advanceBy(1, TimeUnit.SECONDS);
  }

此解决方案是对已接受答案的改进,因为维护了生产代码的质量,完整性和简单性。