Issue
I have a Java program which reads user commands from the terminal (until he types exit
) and performs some computation.
The code looks as follows:
public static void main(String[] args) {
String command = read_from_stdin();
while (!command.equals("exit")) {
String output = execute(command)
System.out.println(output);
command = read_from_stdin();
}
}
private String execute(String command) {...}
The question is: how do I test the private execute
method?
Test through the public
main
function. That requires to feed the input into the main program not from the terminal but from some file. Probably this test will be not a Java Unit test, rather some shell script. YUCK.Make execute
public
and write Java test for it. Doesn't this break the idea of usingprivate/public
access modifiers?
Any other ideas?
UPDATE
Several comments suggest to refactor execute
into a separate class. So if I do something like this:
class Executor {
public String execute(String command) {...}
}
class Main {
public static void main(String[] args) {
Executor executor = new Executor();
String command = read_from_stdin();
while (!command.equals("exit")) {
String output = executor.execute(command);
System.out.println(output);
command = read_from_stdin();
}
}
}
Then sure, I can now Unit-test the public Executor
api. But isn't this conceptually the same as making execute
public (and if not the same, then why is this better)?
Solution
Sometimes you dont want to go the extra mile of extracting everything out. Sometimes you cannot go for best practices for various reasons.
A good solution to this problem is to make the method package private (remove private). If your test is in the same package, then you can access that method and test it directly.
I would personally also add @VisibleForTesting to make clear that this method is accessible because of testing reasons.
In general this is sometimes which is rarely done and always points to some wrong designs.
Answered By - Loading
Answer Checked By - Terry (JavaFixing Volunteer)