Junior — Middle
What is the difference between using @Spy and @Mock in testing?
sobes.tech AI
Answer from AI
@Mock creates a fully simulated object, where all methods do nothing by default or return default values. This is useful when you need to isolate the class under test from dependencies.
@Spy creates a "spy" on a real object, allowing you to call real methods but also to replace individual methods or verify calls. This is convenient when you want to partially use real behavior and partially replace it.
Example:
List<String> list = new ArrayList<>();
List<String> spyList = Mockito.spy(list);
Mockito.doReturn("mocked").when(spyList).get(0);
System.out.println(spyList.get(0)); // Will output "mocked"
System.out.println(spyList.size()); // Calls the real size() method
Thus, @Mock is a completely fake object, while @Spy is a real object with the ability to replace individual methods.