Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito - how to verify that a mock was never invoked

I'm looking for a way to verify with Mockito, that there wasn't any interaction with a given mock during a test. It's easy to achieve that for a given method with verification mode never(), but I haven't found a solution for the complete mock yet.

What I actually want to achieve: verify in tests, that nothing get's printed to the console. The general idea with jUnit goes like that:

private PrintStream systemOut;  @Before public void setUp() {     // spy on System.out     systemOut = spy(System.out); }  @After public void tearDown() {     verify(systemOut, never());  // <-- that doesn't work, just shows the intention } 

A PrintStream has tons of methods and I really don't want to verify each and every one with separate verify - and the same for System.err...

So I hope, if there's an easy solution, that I can, given that I have a good test coverage, force the software engineers (and myself) to remove their (my) debug code like System.out.println("Breakpoint#1"); or e.printStacktrace(); prior to committing changes.

like image 996
Andreas Dolk Avatar asked Aug 13 '12 14:08

Andreas Dolk


People also ask

Which method in Mockito verifies that no interaction has happened with a mock in Java?

Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.

How do I know if Mockito is working?

Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.


2 Answers

Use this :

import static org.mockito.Mockito.verifyZeroInteractions;  // ...  private PrintStream backup = System.out;  @Before public void setUp() {     System.setOut(mock(PrintStream.class)); }  @After public void tearDown() {     verifyZeroInteractions(System.out);     System.setOut(backup); } 
like image 104
gontard Avatar answered Sep 23 '22 13:09

gontard


verifyZeroInteractions(systemOut); 

As noted in comments, this doesn't work with a spy.

For a roughly equivalent but more complete answer, see the answer by gontard to this question.

like image 41
Don Roby Avatar answered Sep 22 '22 13:09

Don Roby