BaseChoiceStep extends AbstractStep { @Override public boolean run() { answer = null; printMessageWithDefaultAnswer(); ChoicesStorage<T> choicesStorage = new ChoicesStorage<>(getAnswerProvider(), getPossibleChoices(answersStorage)); Map<Integer, String> answersMap = choicesStorage.getAnswersMap(); Optional<Boolean> returnValue = processZeroOrOneAnswer(choicesStorage); if (returnValue.isPresent()) { return returnValue.get(); } printPossibleChoices(answersMap); logger.ok(getPrompt()); Optional<String> answerCandidate = processAnswer(); if (!answerCandidate.isPresent()) { return false; } if (isSkipKey(answerCandidate.get())) { if (answerRequired()) { logger.warn("You can not skip this step."); } else { return true; } } while (!validateAnswer(answersMap, answerCandidate.get())) { logger.warn(getIncorrectChoiceMessage(answersMap)); answerCandidate = processAnswer(); if (!answerCandidate.isPresent()) { return false; } } String answer = answerCandidate.get(); this.answer = getAnswerToSave(choicesStorage, answer); saveAdditionalData(answersStorage, choicesStorage, answer); return true; }  @Override boolean run(); @Override String getAnswer();  }
@Test public void testZeroChoicesAnswerRequired() throws Exception { mockBaseChoiceStep.setConsoleReader(mockConsoleReader("y\n")); mockBaseChoiceStep.setPossibleChoices(Collections.emptyList()); mockBaseChoiceStep.setAnswerRequired(true); assertThat(mockBaseChoiceStep.run(), is(false)); assertThat(logger.getErrorMessages(), hasSize(1)); }
@Test public void testZeroChoicesAnswerOptional() throws Exception { mockBaseChoiceStep.setConsoleReader(mockConsoleReader("y\n")); mockBaseChoiceStep.setPossibleChoices(Collections.emptyList()); mockBaseChoiceStep.setAnswerRequired(false); assertThat(mockBaseChoiceStep.run(), is(true)); assertThat(logger.getWarnMessages(), hasSize(1)); }
@Test public void testExit() throws Exception { mockBaseChoiceStep.setConsoleReader(mockConsoleReader("q\n")); mockBaseChoiceStep.setPossibleChoices(Arrays.asList("one", "two")); assertThat(mockBaseChoiceStep.run(), is(false)); }
@Test public void testExitAfterInvalidAnswer() throws Exception { mockBaseChoiceStep.setConsoleReader(mockConsoleReader("n\nq\n")); mockBaseChoiceStep.setPossibleChoices(Arrays.asList("one", "two")); mockBaseChoiceStep.setValidAnswers(Arrays.asList("1", "2")); mockBaseChoiceStep.setAnswerRequired(true); assertThat(mockBaseChoiceStep.run(), is(false)); }
@Test public void testSkip() throws Exception { mockBaseChoiceStep.setConsoleReader(mockConsoleReader("s\n")); mockBaseChoiceStep.setPossibleChoices(Arrays.asList("one", "two")); mockBaseChoiceStep.setAnswerRequired(false); assertThat(mockBaseChoiceStep.run(), is(true)); }