开发者

JUnit testing System.out values [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Java, Junit - Capture the standard input / Output for use in a unit test

JUnit test for System.out.println()

I have written a piece of code similar to the one below. I want to unit test this method, and right now I am stuck at the System.out part. Lets say that the user input was 12. This would prompt the user with "Wrong number, try again.". Is it possible to test this output, or is this impossible by using JUnit?

        public static int testUserInput() {
            Scanner keyboard = new Scanner(System.in);
            System.out.println("Give a number between 1 and 10");
            int input = keyboard.nextInt();

            while (input < 1 || input > 10) {
                System.out.println("Wrong number, try again.");
                input = keyboard.nextInt();
            }

            return input;
    }

Thanks in开发者_C百科 advance.


System.out is of type java.io.PrintStream. If you can mock or pass another type of PrintStream that can capture the output into a StringReader you can Assert its values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜