Welcome to our comprehensive guide on Mockito Spies! In this lesson, we'll explore a powerful Mockito feature that helps you test your Java code more effectively. Let's dive in!
Mockito Spies are mock objects that record the interactions and allow you to verify them later. They are useful when you want to test methods that interact with external services like databases, APIs, or file systems.
To create a Mockito Spy, you can use the spy() method followed by the instance you want to mock. Let's create a spy for a simple Java class:
import static org.mockito.Mockito.*;
public class MyClass {
private MyDependency dependency;
public MyClass(MyDependency dependency) {
this.dependency = dependency;
}
public void myMethod() {
dependency.myMethodFromDependency();
}
}
public class MyDependency {
public void myMethodFromDependency() {
// Implementation here
}
}
// To create a spy for MyClass
MyClass myClassSpy = spy(new MyClass(mock(MyDependency.class)));In the above example, myClassSpy is a spy for the MyClass instance. The mock(MyDependency.class) creates a mock object for MyDependency.
Once you have a spy, you can verify its interactions using Mockito's verify() method. Here's an example:
myClassSpy.myMethod();
verify(myClassSpy.dependency).myMethodFromDependency();In this example, we call myMethod() on myClassSpy, and then we verify that the corresponding method on dependency was called.
Mockito also allows you to mock static methods. To do this, use the when() method to specify the behavior of the mocked method. Here's an example:
when(MyClass.staticMethod()).thenReturn("Mockito Rocks!");In this example, we're mocking the static method staticMethod() of the MyClass class, and telling Mockito to return "Mockito Rocks!" whenever it's called.
What does Mockito Spy do in Java?
How do you create a Mockito Spy for a Java class?