0

I have a class that only contains a main method which has some System.out.println calls which I need to test. I agree that the design of this class is not great, but I have to leave it as is. I am not sure in Mockito how to test the proper values are being printed. I have seen similar questions answered on StackOverflow, but they are different because the calls to System.out.println is actually in the test and not in the class being tested.

public final class ConnectionPasswordEncryptor {

public static void main(String[] arg) {
    final String usage = "Generate encrypted password using PBEWithMD5AndDES algorithm, "
            + "only one argument is accepted, and it can't be empty.";

    if (arg.length == 1) {
        String pwd = StringUtils.trimToNull(arg[0]);
        if (pwd == null) {
            print(usage);
            return;
        }

        print(PasswordEncryptionUtil.encrypt(pwd));

    }
    else if ((arg.length == 2) && ("-d".equalsIgnoreCase(arg[0]))) {
        print(PasswordEncryptionUtil.decrypt(arg[1]));
    }
    else {
        print(usage);
    }
}

private static void print(final String msg) {
    System.out.println(msg);
}

private ConnectionPasswordEncryptor() {
    // prevent from initialization
}

}

For instance, one test I want to do is to test that the proper message is printed if invalid arguments are sent: String[] arg = new String[] {"xx", "abcd1234"}; ConnectionPasswordEncryptor.main(arg); The call does not return anything, but prints to standard out. How do I retrieve what was printed to standard out?

cicit
  • 439
  • 3
  • 21
  • You can also introduce a `PrintWriter` –  Oct 30 '15 at 14:09
  • I saw that one, but it seemed to be different than mine. I will read through again and see if I can make it apply. – cicit Oct 30 '15 at 14:50
  • OK, I was able to get it to work using the suggestion for capturing the PrintStream using System.setOut. – cicit Oct 30 '15 at 15:27

0 Answers0