In Mockito, the key differences between a Spy and a Mock are as follows:
-
Method Behavior:
- Mock: All methods return default values (null, 0, false) unless explicitly stubbed.
- Spy: Methods call the real implementation unless stubbed.
-
Object State:
- Mock: Operations do not change the state (e.g., adding to a mock list does not actually add anything).
- Spy: Operations change the object's state just like a real object.
-
Creation:
- Mock: Created from a class, not an instance (e.g.,
Mockito.mock(ArrayList.class)). - Spy: Usually created from an instance (e.g.,
Mockito.spy(new ArrayList<>())).
- Mock: Created from a class, not an instance (e.g.,
-
Use Cases:
- Mock: When you want to completely control the behavior and do not need real methods.
- Spy: When you want to use real methods but need to override only some behaviors.
These differences help you choose the right tool for your testing needs based on the specific requirements of your tests.
