Can you run JUnit Tests for a CLI application?

63 views Asked by At

I am relatively new to unit tests in Java and I made an application completely with CLI. Example once starting the application the user is given a set of options like so.

  1. Register
  2. Login . . . Etc etc.

If he choses to login he is transferred to a Register () method that asks for details such as name and surname inside the method itself. I want to know if there is any way lf simulating user input when creating the unit tests or if I have to override the methods so that I can pass values through the arguments and do unit testing that way.

1

There are 1 answers

0
Kayaman On BEST ANSWER

Ideally your code should be written so that it's easy to test, and the method of input doesn't matter. This means that the input should be separated from the business logic, so that when you're writing the tests, you can ignore the input part completely.

For example instead of having a global Scanner and having something like the following, which makes the method dependent on the input method

public void login() {
    String username = scanner.nextLine();
    // check that the username is valid
}

a more testable method without any dependencies to the input method would be

public void login(String username) {
    // check that the username is valid
}

also make sure you understand what constitutes a correct unit test. For this method the obvious tests would be that you can login with valid credentials, and that you can't login with invalid credentials.