The @Spy annotation in JUnit, particularly when used with Mockito, is applied to create a spy on an actual object. A spy is a partial mock, which means that you can mock some methods of the object while retaining the real behavior of other methods.
Here are some common uses of the @Spy annotation:
Partial Mocking:
@Spy private List<String> spyList = new ArrayList<>(); @Test public void testSpy() { spyList.add("Mockito"); Mockito.verify(spyList).add("Mockito"); assertEquals(1, spyList.size()); Mockito.doReturn(100).when(spyList).size(); assertEquals(100, spyList.size()); }
Overriding Real Method Behavior:
@Spy private MyClass myClass = new MyClass(); @Test public void testSpyWithMethodOverride() { Mockito.doReturn("Mocked Value").when(myClass).someMethod(); assertEquals("Mocked Value", myClass.someMethod()); }
Verifying Method Calls:
@Spy private MyClass myClass = new MyClass(); @Test public void testMethodCallVerification() { myClass.someMethod(); Mockito.verify(myClass).someMethod(); }
Combining with @InjectMocks:
@Spy private MyDependency dependency; @InjectMocks private MyService service; @Test public void testService() { Mockito.doReturn("Mocked Result").when(dependency).doSomething(); assertEquals("Mocked Result", service.performAction()); }
Testing Legacy Code:
In summary, the @Spy annotation is useful when you need to control or verify specific behaviors of an actual object while keeping the rest of the object's behavior unchanged.
The above is the detailed content of Uses of @spy annotation in junit testing. For more information, please follow other related articles on the PHP Chinese website!