Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verbose mode on spies in Mockito

Tags:

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.

like image 812
Grzenio Avatar asked Jul 05 '17 09:07

Grzenio


People also ask

How does Mockito spy work?

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.

What is the difference between spy and mock in Mockito?

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.

Why Spy is used in Mockito?

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).


1 Answers

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));
like image 147
stryba Avatar answered Sep 30 '22 00:09

stryba