javaunit-testingmockito

How to test System.out.println(); by mocking


hello I have to practice how to use Mockito can someone please tell me how do we use mock objects to test the console based output testing for example

Random rand = new Random();
int number = 1+rand.nextInt(100);              // random number 1 to 100
Scanner scan = new Scanner(System.in);

for (int i=1; i<=10; i++){                     // for loop from 1 to 10
    System.out.println(" guess "+i+ ":");``
    int guess = scan.nextInt();
    //if guess is greater than number entered 
    if(guess>number)
        System.out.println("Clue: lower");
    //if guess is less than number entered 
    else if (guess<number )
        System.out.println("lue: Higher");
    //if guess is equal than number entered 
    else if(guess==number) {
        System.out.println("Correct answer after only "+ i + " guesses – Excellent!");
        scan.close();
        System.exit(-1);
    }

}

System.out.println("you lost" + number);
scan.close();

Solution

  • First off - the call to System.exit() will break your test.

    Second - not a good idea to mock the System class. It makes more sense to redirect System.out to a fake or stub.

    Third - Reading stuff from System.in will be tricky to do from test as well.

    Apart from that: I've taken the liberty to reduce the code for readability:

    public class WritesOut {
    
        public static void doIt() {
               System.out.println("did it!");
        }
    
    }
    

    Test should test if Line was printed to System.out:

    import static org.junit.Assert.*;
    
    import java.io.ByteArrayOutputStream;
    import java.io.PrintStream;
    
    import org.junit.Test;
    
    public class WritesOutTestUsingStub {
    
        @Test
        public void testDoIt() throws Exception {
            //Redirect System.out to buffer
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            System.setOut(new PrintStream(bo));
            WritesOut.doIt();
            bo.flush();
            String allWrittenLines = new String(bo.toByteArray()); 
            assertTrue(allWrittenLines.contains("did it!"));
        }
    
    }