I need to test the method that needs a scanner input. I did try the other post which involves the same problem but it doesn't work for me I don't know why. It asks for bank branch name to be created and I want to check if it is created with the right name. But it is just stuck waiting for a user input. Thank you in advance.
protected static void createBranches() throws Exception {
String branchName;
boolean check = true;
do {
check = false;
System.out.println("Please enter the branch name: ");
branchName = scanner.nextLine();
for (int x = 0; x < branches.size(); x++) {
if (branchName.equals(branches.get(x).getBranchName())) {
System.out.println("Branch name already exist, Please use a unique one.");
check = true;
}
}
} while (check);
Branches branch = new Branches(branchName);
branches.add(branch);
System.out.println("Branch successfully created.");
}
Here is the test block I tried from searching various issues within stackoverflow.
public void bankTest() throws Exception {
Bank bank = new Bank();
String input = "UnionBank";
InputStream stdin = System.in;
try {
System.setIn(new ByteArrayInputStream(input.getBytes()));
Scanner scanner = new Scanner(System.in);
System.out.println(scanner.nextLine());
} finally {
System.setIn(stdin);
bank.createBranches();
}
Assert.assertEquals("UnionBank", bank.branches.get(0));
}