【问题标题】:UntTest - Mock RxJava object in UseCase ObjectUnitTest - 在用例对象中模拟 RxJava 对象
【发布时间】:2016-04-26 19:13:44
【问题描述】:

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

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()));
    }
}

我写了一个简单的测试:

@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();

    }
}

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

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

【问题讨论】:

标签: android unit-testing mockito rx-java


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2011-04-07
    • 2017-04-07
    • 1970-01-01
    相关资源
    最近更新 更多