Sobes.tech
Junior — Middle

What are the differences between @Spy and @Stub annotations when used in testing?

sobes.tech AI

Answer from AI

Annotations @Spy and @Stub are used in testing to create mock objects, but they have different purposes and behaviors:

  • @Spy — creates a "spy" on a real object. This means that by default, the real methods of the object are called, but it is possible to override the behavior of individual methods if needed. It is used when partial control over the behavior of a real object is required, preserving its logic.

  • @Stub — creates a simple stub object that returns predefined values and contains no real logic. It is usually used to isolate the tested code from external dependencies.

Example with Mockito:

@Spy
List<String> spyList = new ArrayList<>();

// calling spyList.add("test") will invoke the real add method

@Stub
List<String> stubList = mock(List.class);
when(stubList.size()).thenReturn(10);

// stubList.size() will return 10, and other methods do not have real implementations

Thus, @Spy allows controlling and observing a real object, while @Stub completely replaces the object's behavior.