Junior — Middle
Can you tell about your experience using the @Spy annotation in testing?
sobes.tech AI
Answer from AI
The @Spy annotation in Java is used in testing with Mockito to create a partial mock object (spy). Unlike @Mock, which creates a fully mocked object, @Spy allows you to use real methods of the object, but you can override the behavior of individual methods.
This is useful when you want to test a class but control the behavior of some of its methods, for example, to avoid calling external services or heavy operations.
Example of usage:
import static org.mockito.Mockito.*;
public class MyServiceTest {
@Spy
private MyService myService = new MyService();
@Test
public void testPartialMock() {
// Override the behavior of a method
doReturn("mocked result").when(myService).someMethod();
// Calling another method will be real
String result = myService.callAnotherMethod();
// Check the result
assertEquals("expected result", result);
}
}
It is important to remember that for @Spy to work correctly, the object should be either created manually or initialized using MockitoAnnotations or MockitoExtension.