vendredi 11 octobre 2019

Java Command Interpreter Testing

Goal is pretty simple. Being able to test a very simple Command Interpreter.

I'm currently using TestNG to test a Java application that has a command interpreter in its root. But I'm not being able to accomplish this.

As soon as the application starts it enters a loop that processes the user input and chooses where to go from there () and only stops if the user's input equals "exit". The printHelp() method prints all the available commands.

Can you tell me how I should proceed in order to test the printHelp() method in a way to simulate a user's input and getting the right output.

Note: Assume that the printHelp() method is supposed to print the string "All the info needed".

The maven dependency as well as the Main Class are provided below.

pom.xml

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.0.0</version>
    <scope>test</scope>
</dependency>

Java Main Class

public static void main(String args[]){
    menu();
}
private static void menu() {
    Scanner in = new Scanner(System.in);
    String[] fullLine;
    StringConst.CMDS cmd; //enum of prossible cmds

    do {
        System.out.print(StringConst.PROMPT); //aesthetic
        fullLine = in.nextLine().toUpperCase().split(" ");
        cmd = StringConst.CMDS.fromString(fullLine[0]);

        switch (cmd) {
            (...)
            case HELP:
                printHelp();
                break;
            case EXIT:
                System.out.println("Exiting...");
                break;
            default:
                System.err.println(StringConst.NOT_FOUND);
                break;
        }

    } while (!cmd.equals(StringConst.CMDS.EXIT));
}

private static void printHelp() {
    for (StringConst.CMDS cmd : StringConst.CMDS.values()) {
        System.out.println(cmd + " - " + cmd.getDescription());
    }
}

Aucun commentaire:

Enregistrer un commentaire