### Question:
VariableNameExtractor { public Optional<String> extract() { Matcher matcher = VARIABLE_NAME_PATTERN.matcher(expression); if (!matcher.matches()) { return Optional.empty(); } return Optional.of(matcher.group(1)); } VariableNameExtractor(String expression); Optional<String> extract();  }### Answer:
@Test public void shouldExtractVariableName() throws Exception { String name = "A_different_NAME123"; String variable = "${A_different_NAME123}"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertTrue(extracted.isPresent()); assertThat(extracted.get(), containsString(name)); }
@Test public void shouldExtractVariableNameFromWhitespaces() throws Exception { String name = "name"; String variable = " \n\t$ \n\t{ \n\tname \n\t} \n\t"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertTrue(extracted.isPresent()); assertThat(extracted.get(), containsString(name)); }
@Test public void shouldReturnEmptyIfThereIsMoreThanVariable() throws Exception { String variable = "a ${test}"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertFalse(extracted.isPresent()); }
@Test public void shouldReturnEmptyIfVariableNameIsIncorrect() throws Exception { String variable = "${name with space}"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertFalse(extracted.isPresent()); }
@Test public void shouldReturnEmptyIfTwoVariablesPresent() throws Exception { String variable = "${var1} ${var2}"; VariableNameExtractor extractor = new VariableNameExtractor(variable); Optional<String> extracted = extractor.extract(); assertFalse(extracted.isPresent()); }