CredentialInjector { public String replaceCredentials(String code) { if (code == null) { return null; } String replaced = code; Matcher matcher = userpattern.matcher(replaced); while (matcher.find()) { String key = matcher.group(1); UsernamePassword usernamePassword = creds.getUsernamePassword(key); if (usernamePassword != null) { String value = usernamePassword.getUsername(); String quotedValue = Matcher.quoteReplacement(value); replaced = matcher.replaceFirst(quotedValue); matcher = userpattern.matcher(replaced); } } matcher = passwordpattern.matcher(replaced); while (matcher.find()) { String key = matcher.group(1); UsernamePassword usernamePassword = creds.getUsernamePassword(key); if (usernamePassword != null) { passwords.add(usernamePassword.getPassword()); String value = usernamePassword.getPassword(); String quotedValue = Matcher.quoteReplacement(value); replaced = matcher.replaceFirst(quotedValue); matcher = passwordpattern.matcher(replaced); } } return replaced; } CredentialInjector(UserCredentials creds); String replaceCredentials(String code); InterpreterResult hidePasswords(InterpreterResult ret);  }
@Test public void replaceCredentials() { UserCredentials userCredentials = mock(UserCredentials.class); UsernamePassword usernamePassword = new UsernamePassword("username", "pwd"); when(userCredentials.getUsernamePassword("mysql")).thenReturn(usernamePassword); CredentialInjector testee = new CredentialInjector(userCredentials); String actual = testee.replaceCredentials(TEMPLATE); assertEquals(CORRECT_REPLACED, actual); InterpreterResult ret = new InterpreterResult(Code.SUCCESS, ANSWER); InterpreterResult hiddenResult = testee.hidePasswords(ret); assertEquals(1, hiddenResult.message().size()); assertEquals(HIDDEN, hiddenResult.message().get(0).getData()); }
@Test public void replaceCredentialNoTexts() { UserCredentials userCredentials = mock(UserCredentials.class); CredentialInjector testee = new CredentialInjector(userCredentials); String actual = testee.replaceCredentials(null); assertNull(actual); }