NoteViewModel extends ViewModel<String, NoteModel> { public void save() { boolean titleValid = checkMandatory(model.getTitle(), model.getTitleError()); boolean textValid = checkMandatory(model.getText(), model.getTextError()); if (titleValid && textValid) { sending.set(true); backgroundExecutor.execute(new Runnable() { @Override public void run() { try { Note note = new Note(null, model.getTitle().get(), model.getText().get()); String noteId = model.getNoteId(); if (noteId == null) { noteId = noteSaver.createNewNote(note).getObjectId(); model.setNoteId(noteId); } else { noteSaver.save(noteId, note); } hideSendProgressAndShoMessage(R.string.note_saved); } catch (RetrofitError e) { hideSendProgressAndShoMessage(R.string.error_saving_note); } } }); } } NoteViewModel(Executor backgroundExecutor, Executor uiExecutor, NoteLoader noteLoader, NoteSaver noteSaver, MessageManager messageManager); @NonNull @Override NoteModel createModel(); @Override void resume(); void reloadData(); void save(); @Override ActivityResult onBackPressed(); final ObservableBoolean loading; final ObservableBoolean sending; }
@Test public void testValidation() { NoteModel model = viewModel.initAndResume(TestData.ID_A); model.getTitle().set(""); model.getText().set(""); viewModel.save(); assertThat(model.getTitleError().get()).isEqualTo(R.string.mandatory_field); assertThat(model.getTextError().get()).isEqualTo(R.string.mandatory_field); verify(noteSaver, never()).save(anyString(), any(Note.class)); verify(messageManager, never()).showMessage(any(ActivityHolder.class), anyInt()); }
@Test public void testSaveData() { NoteModel model = viewModel.initAndResume(TestData.ID_A); model.getTitle().set(TestData.NEW_TITLE); model.getText().set(TestData.NEW_TEXT); viewModel.save(); verify(noteSaver).save(eq(TestData.ID_A), captor.capture()); assertThat(captor.getValue()) .isEqualToComparingFieldByField(new Note(null, TestData.NEW_TITLE, TestData.NEW_TEXT)); verify(messageManager).showMessage(any(ActivityHolder.class), eq(R.string.note_saved)); }
@Test public void testErrorSavingData() { when(noteSaver.save(anyString(), any(Note.class))) .thenThrow(TestData.networkError()); NoteModel model = viewModel.initAndResume(TestData.ID_A); model.getTitle().set(TestData.NEW_TITLE); model.getText().set(TestData.NEW_TEXT); viewModel.save(); verify(messageManager).showMessage(any(ActivityHolder.class), eq(R.string.error_saving_note)); }
@Test public void testCreateNewNote() { when(noteSaver.createNewNote(any(Note.class))) .thenReturn(new SaveResponse(TestData.NEW_ID)); NoteModel model = viewModel.initAndResume(); verify(noteLoader, never()).load(anyString()); model.getTitle().set(TestData.NEW_TITLE); model.getText().set(TestData.NEW_TEXT); viewModel.save(); verify(noteSaver).createNewNote(captor.capture()); assertThat(captor.getValue()) .isEqualToComparingFieldByField(new Note(null, TestData.NEW_TITLE, TestData.NEW_TEXT)); assertThat(model.getNoteId()).isEqualTo(TestData.NEW_ID); }