Java Tutorial: Mockito Spies 🎯

beginner
12 min

Java Tutorial: Mockito Spies 🎯

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!

What are Mockito Spies? 💡

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.

Why Use Mockito Spies? 📝

  • Isolate code: By mocking dependencies, you can test your code in isolation, avoiding the complexity of real-world interactions.
  • Simplify tests: Mockito Spies make it easier to create and manage test doubles, reducing the complexity of your test suite.
  • Improve test reliability: By controlling the behavior of mocked dependencies, you can ensure consistent test results, even as the underlying dependencies change.

Creating a Mockito Spy 🎯

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:

java
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.

Verifying Interactions with Mockito Spies 📝

Once you have a spy, you can verify its interactions using Mockito's verify() method. Here's an example:

java
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.

Mocking Static Methods with Mockito Spies 💡

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:

java
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.

Quick Quiz
Question 1 of 1

What does Mockito Spy do in Java?

Quick Quiz
Question 1 of 1

How do you create a Mockito Spy for a Java class?