RandomPasswordGenerator { public static char[] generatePassword(int minLen, int maxLen, int noOfCAPSAlpha, int noOfDigits, int noOfSplChars) { if (minLen > maxLen) { throw new IllegalArgumentException("Min. Length > Max. Length!"); } if ((noOfCAPSAlpha + noOfDigits + noOfSplChars) > minLen) { throw new IllegalArgumentException("Min. Length should be atleast sum of (CAPS, DIGITS, SPL CHARS) Length!"); } Random rnd = new Random(); int len = rnd.nextInt(maxLen - minLen + 1) + minLen; char[] pswd = new char[len]; int index; for (int i = 0; i < noOfCAPSAlpha; i++) { index = getNextIndex(rnd, len, pswd); pswd[index] = ALPHA_CAPS.charAt(rnd.nextInt(ALPHA_CAPS.length())); } for (int i = 0; i < noOfDigits; i++) { index = getNextIndex(rnd, len, pswd); pswd[index] = NUM.charAt(rnd.nextInt(NUM.length())); } for (int i = 0; i < noOfSplChars; i++) { index = getNextIndex(rnd, len, pswd); pswd[index] = SPL_CHARS.charAt(rnd.nextInt(SPL_CHARS.length())); } for (int i = 0; i < len; i++) { if (pswd[i] == 0) { pswd[i] = ALPHA.charAt(rnd.nextInt(ALPHA.length())); } } return pswd; }  static char[] generatePassword(int minLen, int maxLen, int noOfCAPSAlpha, int noOfDigits, int noOfSplChars);  }
@Test(expected = IllegalArgumentException.class) public void testMinGreaterThanMax() throws Exception { int min = 3; int max = 2; RandomPasswordGenerator.generatePassword(min, max, 0, 0, 0); }
@Test(expected = IllegalArgumentException.class) public void testMaxLessThanTotal() throws Exception { int max = 2; int caps = 2; int digits = 2; int special = 2; RandomPasswordGenerator.generatePassword(0, max, caps, digits, special); }
@Test public void testPasswordBetweenMinAndMax() { int min = 3; int max = 8; char[] testPassword = RandomPasswordGenerator.generatePassword(min, max, 0, 0, 0); String strTestPassword = new String(testPassword); assertThat(strTestPassword.length(), lessThanOrEqualTo(max)); assertThat(strTestPassword.length(), greaterThanOrEqualTo(min)); min = 2; max = 2; testPassword = RandomPasswordGenerator.generatePassword(min, max, 0, 0, 0); strTestPassword = new String(testPassword); assertThat(strTestPassword.length(), lessThanOrEqualTo(max)); assertThat(strTestPassword.length(), greaterThanOrEqualTo(min)); }