UntTest - 在用例对象中模拟 RxJava 对象 [英] UntTest - Mock RxJava object in UseCase Object

查看:36
本文介绍了UntTest - 在用例对象中模拟 RxJava 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试 UseCase 对象,在这个特定情况下有一个 LoginUseCase,它看起来像这样:

I want to test UseCase object, in this specific case there is a LoginUseCase, which looks like this:

public class LoginUseCase implements RxUseCase<AuthResponse, AuthCredentials> {

    ApiManager mApiManager;

    public LoginUseCase(ApiManager apiManager) {
        mApiManager =apiManager;
    }

    @Override
    public Observable<AuthResponse> execute(final AuthCredentials authCredentials) {
        return Observable.just(1)
                .delay(750, TimeUnit.MILLISECONDS)
                .flatMap(l -> mApiManager.login(authCredentials.getLogin(), authCredentials.getPassword()));
    }
}

我写了一个简单的测试:

I wrote simple test:

@RunWith(MockitoJUnitRunner.class)
public class LoginUseCaseTest {

    private LoginUseCase mLoginUseCase;
    @Mock ApiManager mApiManager;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        mLoginUseCase = new LoginUseCase(mApiManager);
    }


    @Test
    public void testShouldThrowsError() throws Exception {
        TestSubscriber<AuthResponse> testSubscriber = new TestSubscriber<>();
        doReturn(Observable.error(new Throwable())).when(mApiManager).login("", "");
        mLoginUseCase
            .execute(new AuthCredentials("", ""))
            .subscribe(testSubscriber);
        testSubscriber.assertNoErrors();

    }
}

但是这个测试总是通过,我不知道在这种情况下如何观察到模拟错误.

But this test always passes and I don't know how mock error observable in this case.

编辑:根据 SkinnyJ,我已更改 testShouldThrowsError(),但测试仍然通过,有任何建议吗?

EDIT: I've chaged testShouldThrowsError() according to SkinnyJ, but test still passes, any sugestions?

推荐答案

在断言之前,您需要对您的测试订阅者调用 awaitTerminalEvent().因为现在,您安排延迟在 Schedulers.computation 上运行,并且您的测试方法在 observable 完成之前成功完成.

You need to call awaitTerminalEvent() on your test subscriber before assertions. Because now, you schedule a delay to be run on Schedulers.computation and your test method successfully completes before completion of observable.

替代方法是将调度程序作为参数传递给 execute 方法,或将调度程序存储在您的用例中.这样,在测试期间您可以通过 Schedulers.immediate() 并且您的测试将在当前线程上运行(这将阻止执行指定的延迟).

Alternative approach would be to pass scheduler as argument to execute method, or store scheduler in your usecase. This way, during test you can pass Schedulers.immediate() and your test will run on current thread (which will block execution for specified delay).

最后一种方法是在 observable 上调用 toBlocking(),但我认为传递调度程序是首选.并且无法将此运算符添加到您当前的 observable 中.

And last approach is to call toBlocking() on observable, but I think that passing scheduler is preferred choice. And there is no way to add this operator to your current observable.

这篇关于UntTest - 在用例对象中模拟 RxJava 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆