我已经使用 Scanner 类构建了一个交互式 Java 应用程序。我想用 Junit 5 测试它。
在搜索了之后,我编写了用于模拟 shell 的测试用例。测试用例针对第一个命令运行并停留在 main 方法中。它不会返回控制台。由于它,我的后续命令没有执行。
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
while (true) {
final String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
printMsg("Exiting the application..");
System.exit(1);
}
else {
printMsg("User Input >>>> " + input);
final CommandProcessor commandProcessor = new CommandProcessor();
try {
commandProcessor.process(input);
}
catch (Exception e) {
System.out.println("An error occurred - " e.getLocalizedMessage() + ". Please try again.");
}
}
}
}
public class CommandProcessor {
public void process(final String input) throws Exception {
//Some validations
final CommandHandler commandHandler = CommandHandlerFactory.getHandler(inputCommand);
commandHandler.execute(args);
}
}
}
public class CreateCommandHandler extends CommandHandler {
@Override
void handle(final String[] args) throws Exception {
final int units = Integer.parseInt(args[1]);
System.out.println("Created units " + units);
}
}
class ApplicationTest {
private static final InputStream systemIn = System.in;
private static final PrintStream systemOut = System.out;
private static InputStream testIn;
private static OutputStream testOut;
@BeforeEach
public void setUpOutput() {
testOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(testOut));
}
private void provideInput(String data) {
testIn = new ByteArrayInputStream(data.getBytes());
System.setIn(testIn);
}
private String getOutput() {
return testOut.toString();
}
@AfterEach
public void resetSystemInputOutput() {
System.setIn(systemIn);
System.setOut(systemOut);
}
@Test
public void testCreateSuccess() {
String testString = "create 2";
provideInput(testString);
Application.main(new String[0]);
assertEquals("Created units - 2", getOutput());
//Verifying the empty state. Another handler is invoked for it.
provideInput("status");
assertEquals("No units assigned", getOutput());
//exiting the shell.
provideInput("exit");
}
// @Test
public void testStatusAfterCreateParkingLotSuccess() {
String testString = "status";
provideInput(testString);
Application.main(new String[0]);
assertEquals(AppConstants.PARKING_LOT_IS_EMPTY, getOutput());
resetSystemInputOutput();
provideInput("exit");
Application.main(new String[0]);
}
@AfterAll
public static void exit() {
//System.setIn(new ByteArrayInputStream("exit".getBytes()));
}
}
单元测试 testCreateSuccess() 只运行 create 命令,然后一直等待下一个输入。控件没有返回到测试以发送下一个命令。为什么它在这里表现不同?当我运行 shell 时,我可以逐个输入命令。如何在测试用例中实现相同的行为?我需要使用 Junit 运行和验证 5-6 个命令。任何帮助表示赞赏。我还想从 txt 文件中处理这些命令。