2

I can't seem to test this function out. If the value doesn't match the regex it would go to the else statement. But the else statement has a scanner so the JUnit class would ask to enter a valid value until it matches with the regex. Is there a way to stop the function before it goes to else?

public String addName(String name){

    String setName = "";

    while(true) {
        if(name.matches("[a-zA-Z ]{1,30}")) {   
            setName = name;
            break;
        } else {
            System.out.println("Please enter a valid name");
            name = scan.nextLine();
        }
    }

    return setName;
}

@Test
public void test(){

    String name = "1001";
    String setname = person.addName(name);
    assertEquals(name,setname);

}
JunitHelp
  • 53
  • 5
  • 1
    Possible duplicate of [JUnit testing with simulated user input](http://stackoverflow.com/questions/6415728/junit-testing-with-simulated-user-input) – Catchwa Mar 30 '17 at 03:04
  • @Catchwa I don't want to simulate a user input, I just want the test go through regex, if it doesn't go through then the regex test it's a success else it's a fail – JunitHelp Mar 30 '17 at 03:57
  • 2
    you would need to significantly change the logic of your actual program to achieve what you say you want i.e. completely decouple the regex checking from the insistence that you get a valid name - then you only unit test the former. I still think that the steps outlined in the question I linked are an appropriate solution. – Catchwa Mar 30 '17 at 04:12

0 Answers0