What is the difference between these two declarations in Mockito?
@Mock(answer = Answers.CALLS_REAL_METHODS) ArrayList<String> mock; @Spy ArrayList<String> spy;
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.
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