Junior — Middle
How do the Mock and Spy annotations differ in testing?
sobes.tech AI
Answer from AI
In Java testing, the annotations @Mock and @Spy are used to create test doubles, but with different behaviors:
-
@Mockcreates a fully mocked object, where all methods do nothing by default (return default values). Its behavior is manually configured usingwhen(...).thenReturn(...). It is used to isolate the tested code from dependencies. -
@Spycreates a partially mocked object, which calls real methods of the original object unless overridden. This is useful when you want to test part of an object's behavior while preserving the real logic.
Example:
@Mock
List<String> mockedList;
@Spy
ArrayList<String> spyList = new ArrayList<>();
// mockedList.add("test") will not change the list's state, behavior needs to be configured
// spyList.add("test") will call the real add method and add the element