When creating normal mocks you can make the mock verbose for easier debugging, e.g.:
List mockWithLogger = mock(List.class, withSettings().verboseLogging());
Example taken from Mockito documentation. How can I achieve similar result when using spies? I.e. I would like to write something like:
List spyWithLogger = spy(new MyList(), withSettings().verboseLogging());
but it doesn't seem to compile.
A Mockito spy is a partial mock. We can mock a part of the object by stubbing few methods, while real method invocations will be used for the other. By saying so, we can conclude that calling a method on a spy will invoke the actual method, unless we explicitly stub the method, and therefore the term partial mock.
Mocks are used to create fully mock or dummy objects. It is mainly used in large test suites. Spies are used for creating partial or half mock objects. Like mock, spies are also used in large test suites.
Mockito Spy A Spy is like a partial mock, which will track the interactions with the object like a mock. Additionally, it allows us to call all the normal methods of the object. Whenever we call a method of the spy object, the real method will be invoked(unless it is stubbed).
Looking at the implementation of spy the following should work:
MyList myList = new MyList();
List spyWithLogger = mock(myList.getClass(), withSettings()
.verboseLogging()
.spiedInstance(myList)
.defaultAnswer(CALLS_REAL_METHODS));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With