TodoListViewModelImpl extends BaseViewModel implements TodoListViewModel { @Override public Observable<Todo> checkChangeItem(TodoItemViewModel todoItemViewModel) { Todo todo = todoItemViewModel.getTodo(); return configWithScheduler(mRepository.createOrUpdate(todo)) .doOnSubscribe(todo::switchComplete) .doOnError(throwable -> todo.switchComplete()) .doOnNext(id -> mTodoItems.set(mTodoItems.indexOf(todoItemViewModel), todoItemViewModel)); } TodoListViewModelImpl(@NonNull Context mContext, @NonNull TodoRepository todoRepository,
                                 @NonNull RxUtils.SchedulerHolder schedulerHolder); @Override ObservableInt getAlertVisibility(); @Override ObservableList<TodoItemViewModel> getTodoItems(); @Override @SuppressWarnings("Anonymous2MethodRef") Observable fetchAllTodo(); @Override Observable<Todo> checkChangeItem(TodoItemViewModel todoItemViewModel); @Override void insert(Todo todo); @Override void update(Todo todo); @Override Observable<Boolean> deleteItem(int position);  }
@Test public void testCheckChangeItemSuccess() throws Exception { when(mRepository.createOrUpdate(any(Todo.class))).thenAnswer(invocation -> { Object[] args = invocation.getArguments(); return Observable.just((Todo) args[0]); }); fetchData(); mViewModel.checkChangeItem(mItemViewModelList.get(0)).toBlocking().single(); assertTrue(mItemViewModelList.get(0).isCompleted()); }
@Test public void testCheckChangeItemFail() throws Exception { when(mRepository.createOrUpdate(any(Todo.class))) .thenReturn(Observable.create((Observable.OnSubscribe<Todo>) subscriber -> { try { throw new Exception("error"); } catch (Exception ex) { subscriber.onError(ex); } })); fetchData(); mViewModel.checkChangeItem(mItemViewModelList.get(0)).subscribeOn(Schedulers.immediate()) .subscribe(todo -> { fail("Should not success"); }, throwable -> { assertEquals("error", throwable.getMessage()); }); assertFalse(mItemViewModelList.get(0).isCompleted()); }