I have a unit test that is failing and I\'m unsure why. I want to be able to see all invocations on the mock that occur in the System Under Test. This is not the behavior th
This feature is builtin since Mockito 1.9.5. Just use
mock(ClassToMock.class, withSettings().verboseLogging())
From Mockito 1.9.5
you can inspect a mock with MockingDetails Mockito.mockingDetails(Object mockToInspect).
You can either dig into the MockingDetails
properties by invoking : getMock()
, getStubbings()
, getInvocations()
and so for ... or simply use the printInvocations()
method that returns :
a printing-friendly list of the invocations that occurred with the mock object. Additionally, this method prints stubbing information, including unused stubbings. For more information about unused stubbing detection see MockitoHint.
For example with JUnit 5 :
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.Mock;
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class FooTest {
Foo foo;
@Mock
Bar bar;
@Test
void doThat() throws Exception {
Mockito.when(bar.getValue())
.thenReturn(1000L);
// ACTION
foo.doThat();
// ASSERTION
// ...
// add that to debug the bar mock
System.out.println(mockingDetails(bar).printInvocations());
}
}
And you get an output such as :
[Mockito] Interactions of: Mock for Bar, hashCode: 962287291 1. bar.getValue(); -> at Foo.doThat() (Foo.java:15) - stubbed -> at FooTest.doThat(FooTest.java:18)
Note that the classes with a referenced line in the output are links to your source code/test class. Very practical.