防止JUnit测试在while循环中陷入困境



我目前正在为Replit.com的教育团队上的一些作业编写一些JUnit测试。我相信,我有一个测试被卡住了,因为主方法中有一个while循环。根据程序,如果第一个输入有效,则运行测试。如果第一个输入无效,则测试会被卡住。

测试如下:

@Test
public void validPW(){
String correctOutput = "Enter a password >>  Not enough uppercase letters!nNot enough digits!nReEnter a password >> Valid passwordnGoodbye!";
try{
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//PrintStream ps = new PrintStream(baos);
System.setOut(new PrintStream(baos, false, "UTF-8"));
// IMPORTANT: save old Sytem.in!
InputStream is = System.in;
// Set new System.in
System.setIn(new ByteArrayInputStream("Iljvm4nVaGN76jsn".getBytes()));
// Calling main method should save main method's output as string literal to baos.
String[] requiredArray = {"Hello", "There"};
ValidatePassword.main(requiredArray);
// Put things back
System.out.flush();
System.setOut(old);
//Restore
System.setIn(is);

assertEquals(correctOutput, baos.toString());
}catch(IOException ioe){
new IOException("i/o problem - test not executedn");
}
}

这是程序:

import java.util.*;
public class ValidatePassword {
public static void main(String[] args) {
String passWord;
boolean Valid = false;
final int NUM = 2; // two digits and two Upper case letters
// counters to count the required digits and letters
int upperCount = 0;
int lowerCount = 0;
int digitCount = 0;
while (!Valid) {

Scanner in = new Scanner(System.in);
int numSpaces = 0;
System.out.print("Enter a password >> ");
passWord = in.next();
in.nextLine(); // capture dangling newline char.
// Using a for loop to iterate over each character in the String
for (int i = 0; i < passWord.length(); i++) {
char ch = passWord.charAt(i);
if (Character.isUpperCase(ch)){ // Using the Character class's methods
upperCount++;
}
else if (Character.isLowerCase(ch)){
lowerCount++;
}
else if (Character.isDigit(ch)){
digitCount++;
}
}
if (upperCount >= NUM && lowerCount >= 3 && digitCount >= NUM) {
System.out.println("Valid passwordnGoodbye!");
Valid = true;   
} else {                
if (upperCount < NUM)
System.out.println("Not enough uppercase letters!");
if (lowerCount < 3)
System.out.println("Not enough lowercase letters!");
if (digitCount < NUM)
System.out.println("Not enough digits!");
System.out.print("Re");
// Resetting the counters if not a valid password
upperCount = 0;
lowerCount = 0;
digitCount = 0;
}            
}
}
}

首先,ValidatePassword中的代码试图读取超出其末尾的输入流,因此扫描仪初始化需要移出循环,并且需要检查条件in.hasNextLine()

此外,最好使用行passWord = in.nextLine();的单个读取而不是对in.next(); in.nextLine();的读取。

这两个修复程序应该可以解决循环不正确的问题。

Scanner in = new Scanner(System.in);
while (!Valid && in.hasNextLine()) {

int numSpaces = 0;
System.out.print("Enter a password >> ");
passWord = in.nextLine();
//in.nextLine(); // capture dangling newline char.
// ... keep the rest as is

最后,correctOutput需要被固定,assertEquals才能成功完成。

最新更新