0

I try to write JUnit tests in IntelliJ for an application, that modifies a String. Now how can I test one particular print on the console?

Let's assume the start-string is stored in args[0] as "Hello World" and we have a method that can change a single letter in the string. The string will be printed out after the execution of the method.

public class modifyString {
    public static void main(String[] args) {

          Scanner scanner = new Scanner(System.in);

          while(true) {
              // Print the string
              System.out.println(args[0]);

              // Wait for a userinput that only contains two chars,
              // e.g. '0h' <- 'Change the index 0 to 'h''
              // (the order of the chars is unimportant)
              String input = scanner.nextLine();

              if(preconditionFullfilled(input)) {
                  executeOperation(input, args);
              }
         }
    }
}

For example: The expected output for the input '0h' with a 'Hello World' string in args[0] should be 'hello World'.

How do I write a JUnit test to test this particular result?

theDude
  • 1
  • 1
  • 1
    You shouldn't be testing prints to console. You may consider testing method calls, the results of which are printed to console. – Joe C Dec 29 '18 at 18:29

1 Answers1

2

As far as I know there is no way to test the already printed output if you use System.out. for printing. I think it could be theoretically possible if you use another PrintStream class, but I would highly recommend you to change your Code in a way that you work with Strings or StringBuilders as return types and do the printing separately. So you can easily write Unit tests for all your methods.

In addition if you want to test the written output you could write the output in e.g a .txt file and them comparing the content with a expected result file. However this goes into integration tests and would be basically overkill here.

I hope this help you a bit. If you have further questions please ask. Regards, Kai

Kai Karren
  • 31
  • 1
  • 5