NSImageView
,这很奇怪
方法:
onCompleted
测试:
void load() {
fetchData().subscribeOn(getIoScheduler())
.observeOn(getMainThreadScheduler())
.doOnError(throwable -> System.out.println("doOnError " + throwable))
.subscribe(new Subscriber<MyObject>() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println("onError " + e);
handleError();
}
@Override
public void onNext(MyObject myObject) {
handleSuccess(myObject);
}
});
}
在控制台中,仅打印出@Test
public void load() {
Mockito.doReturn(Schedulers.immediate())
.when(presenter)
.getMainThreadScheduler();
Mockito.doReturn(Schedulers.immediate())
.when(presenter)
.getIoScheduler();
// a) Success case
MyObject object = Mockito.mock(MyObject.class);
Mockito.doReturn(Observable.just(object))
.when(presenter)
.fetchData();
presenter.load();
Mockito.verify(presenter)
.fetchData();
Mockito.verify(presenter)
.handleSuccess(object);
Mockito.reset(presenter);
// b) Error case
Mockito.doReturn(Observable.error(new Exception("dummy exception"))).when(presenter)
.fetchData();
presenter.load();
Mockito.verify(presenter)
.handleError();
}
。
有趣的是,当我删除测试成功方案的代码时,它按预期工作:
onCompleted
输出:
@Test
public void load() {
Mockito.doReturn(Schedulers.immediate())
.when(presenter)
.getMainThreadScheduler();
Mockito.doReturn(Schedulers.immediate())
.when(presenter)
.getIoScheduler();
// b) Error case
Mockito.doReturn(Observable.error(new Exception("dummy exception"))).when(presenter)
.fetchData();
presenter.load();
Mockito.verify(presenter)
.handleError();
}
我在这里缺少什么?我是否应该在测试错误情景之前重置一些内容?
我正在使用RxJava 1.3.4
答案 0 :(得分:3)
这里的关键可能是:
Mockito.reset(presenter);
调用它会删除与线程相关的任何模拟,因为它在测试方法开始时只设置一次,并且在重置后不会再次设置模拟文件。
老实说,测试成功和错误测试用例应该是两种不同的测试场景,可以省略重置模拟。
第一种情况:
@Test
public void loadSuccess() {
Mockito.doReturn(Schedulers.immediate())
.when(presenter)
.getMainThreadScheduler();
Mockito.doReturn(Schedulers.immediate())
.when(presenter)
.getIoScheduler();
MyObject object = Mockito.mock(MyObject.class);
Mockito.doReturn(Observable.just(object))
.when(presenter)
.fetchData();
presenter.load();
Mockito.verify(presenter)
.fetchData();
Mockito.verify(presenter)
.handleSuccess(object);
}
第二个(错误)场景:
@Test
public void loadError() {
Mockito.doReturn(Schedulers.immediate())
.when(presenter)
.getMainThreadScheduler();
Mockito.doReturn(Schedulers.immediate())
.when(presenter)
.getIoScheduler();
Mockito.doReturn(Observable.error(new Exception("dummy exception"))).when(presenter)
.fetchData();
presenter.load();
Mockito.verify(presenter)
.handleError();
}