【发布时间】: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(),但测试仍然通过,有什么建议吗?
【问题讨论】:
-
虽然我不知道为什么这里需要延迟,但是你可以使用reactivex.io/documentation/operators/timer.html操作符而不是+延迟,这样会更短。
标签: android unit-testing mockito rx-java