RxJava TestSubscriber / TestSingleSubscriber

时间:2016-07-11 09:13:54

标签: java android unit-testing junit rx-java

我为Single运营商编写测试时遇到了麻烦。出于某种原因,Subscriber在创建后就被标记为unsubscribed

代码片段:

public abstract class OneShotUseCase<T> {

    @NonNull
    private CompositeSubscription subscription = new CompositeSubscription();

    public void cancel() {
        subscription.clear();
    }

    public void execute(@NonNull SingleSubscriber<T> subscriber) {
        subscription.add(
                build().subscribe(subscriber)
        );
    }

    @NonNull
    protected abstract Single<T> build();
}

测试:

@RunWith(JUnit4.class)
public class OneShotUseCaseTest {

    private OneShotUseCase<String> sut;


    @Before
    public void setUp() {
        sut = new TestUseCase();
    }

    @Test
    public void shouldBuildUseCase() {
        final TestSingleSubscriber<String> stringTestSingleSubscriber = new TestSingleSubscriber<>();

        sut.execute(stringTestSingleSubscriber);

        stringTestSingleSubscriber.assertValue("Test value");
    }

    @Test
    public void shouldCancelUseCase() {
        final TestSingleSubscriber<String> stringTestSingleSubscriber = new TestSingleSubscriber<>();

        sut.execute(stringTestSingleSubscriber);
        sut.cancel();

        stringTestSingleSubscriber.assertUnsubscribed();
    }


    private static class TestUseCase extends OneShotUseCase<String> {

        @NonNull
        @Override
        protected Single<String> build() {
            return Single.just("Test value");
        }
    }
}

作为TestSingleSubscriber,我使用以下代码:https://github.com/ReactiveX/RxJava/pull/3834

我的测试在stringTestSingleSubscriber.assertUnsubscribed();

行失败

我试着挖掘一下,但我之前没有发现任何问题。

我对 RxJava Single 的理解是否有问题?

值得一提的是,使用Observable<T>代替Single的非常相似的代码可以完美地运行。

我希望在这里找到一些如何使其发挥作用的想法。

1 个答案:

答案 0 :(得分:1)

感谢伟大的RxJava社区,我可以发布工作解决方案:

 public void execute(@NonNull SingleSubscriber<T> subscriber) {
        build().subscribe(subscriber);
        subscription.add(subscriber);
    }

问题在于实施细节subscribe方法如何适用于SingleObservable

问题在Github上解决了,所以我发布链接: https://github.com/ReactiveX/RxJava/issues/4193