JUnit test for console input and output

I have only one method main. How to check System.out.println() and replace Scanner to input values automatically using JUnit?

P.S. Please, provide some solutions...

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int[] arr = new int[4];

    for (int i = 0; i < arr.length; i++) {
        arr[i] = scanner.nextInt();

    for (int i = 0; i < arr.length; i++) {
        int res = 0;
        int k = 0;
        int num = arr[i];


Ideally, extract the awkward dependencies so that you can test without them. Change main to simply:

public static void main(String[] args) {
  doWork(new Scanner(System.in), System.out);

// TODO: Rename to something meaningful
public static void doWork(Scanner input, PrintStream output) {
  // Remainder of code

(Consider using a Writer instead of a PrintStream for output.)

Then you don't really need to unit test main - but you can test doWork using a Scanner based on a StringReader, and output based on a StringWriter, providing whatever input you want and checking the output.

Need Your Help

How to scan in/to a Webapplication

web-applications ocr barcode archiving image-scanner

I have contemplating how to handle paper document input in Webapps for some time. The main problem is how to unify metadata and a scanned PDF. For the sake of this example I will present a hypothet...

Creating a parametrized module over a parametrized module

ocaml functor

I'm trying to write a module that implements algorithms on another module that may be implemented in various ways. So my thinking was to write the first module as

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.