Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Mockito @Spy and @Mock(answer = Answers.CALLS_REAL_METHODS)

Tags:

What is the difference between these two declarations in Mockito?

@Mock(answer = Answers.CALLS_REAL_METHODS) ArrayList<String> mock;  @Spy ArrayList<String> spy; 
like image 498
Andrei Amarfii Avatar asked Nov 04 '15 07:11

Andrei Amarfii


1 Answers

The former CALLS_REAL_METHODS style creates an uninitialized object; no constructors are run and no fields are set. Generally this syntax is unsafe, as real implementations will interact with uninitialized fields that may constitute an invalid or impossible state.

The latter @Spy style allows you to call a constructor of your choice, or Mockito will try to call a no-arg constructor if the field is uninitialized. The fields are then copied into a generated Spy (that extends the spied-on type), allowing for much safer and more-realistic interactions.


Requisite reminder: Don't actually mock Java collections outside of toy examples, and don't forget to use doReturn syntax when overriding spies and CALLS_REAL_METHOD mocks or else you'll call the real method within the when call.

like image 168
Jeff Bowman Avatar answered Oct 12 '22 09:10

Jeff Bowman