1

Let's say I have the following class:

class MyClass { 
    public MyClass(){
    }
    public void hello() {
       System.out.println("hello");
    }
}

and I want to test 'hello' method:

@Test
public void testHello() {
    MyClass mc = new MyClass();
    mc.hello();
}

Now, I want to spy System.out.println and make sure that this method was called with "hello" as argument. How do I do it?

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183

1 Answers1

2

System.out is actually an instance of PrintStream, so my approach would be to create a mock of this class and direct output to that using the System.setOut method:

PrintStream outMock = Mockito.mock(PrintStream.class);
System.setOut(outMock);
System.out.println("Hello");
Mockito.verify(outMock).println("Hello");

Remember to restore the previous PrintStream instance after the test, preferably in a finally clause.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60