Issue
I need to test a method that takes an input TextFild, how can I change the input to ArrayList to get the data. I am getting an error that says
java.lang.ClassCastException: class java.lang.Character cannot be cast to class
private boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
Matcher matcher = p.matcher(passwordField.getText());
if (matcher.matches()) {
return true;
} else {
lblMessage.setText("Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
my solution
public class TestCases {
ArrayList<Character> characters = new ArrayList<>();
public boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
for (int i = 0; i < characters.size(); i++) {
Object j = characters.get(i);
Matcher matcher = p.matcher((CharSequence) j);
if (matcher.matches()) {
return true;
} else {
System.out.println(
"Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters "););
return false;
}
}
return false;
}
public void setEmail(ArrayList<Character> list) {
characters = list;
}
}
Junit class
@Test
void test() {
String password= "Kd123456";
ArrayList<Character> paswordField=new ArrayList<>();
for(int i= 0 ; i<password.length(); i++){
paswordField.add(password.charAt(i));
}
TestCases valid= new TestCases();
valid.setEmail(paswordField);
assertEquals(true,valid.validatePassword());
}
}
Solution
if hope this will help you !!
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class TestCases {
public boolean validatePassword(String s) {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-z0-9 ]).{8,15})",
Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(s);
if (matcher.matches()) {
return true;
} else {
System.out.println("Please enter a valid password \n"
+ "(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
@Test
public void test() {
String password = "Kd12@3456";
TestCases valid = new TestCases();
assertEquals(true, valid.validatePassword(password));
}
}
Answered By - rahul sharma