Introduction
In this chapter, we will learn about creating mocks with Mockito. Mocks are a fundamental part of unit testing, as they allow you to isolate the code you are testing from its dependencies. This makes your tests more reliable and focused.
What is a Mock?
A mock is a fake version of a real object that simulates the behavior of the actual object. In unit testing, mocks are used to mimic the behavior of real objects to test how your code interacts with its dependencies. Mocks allow you to define how the object should behave when its methods are called, providing consistent and predictable responses.
Creating Mocks with Mockito
Step 1: Add Mockito Dependency
First, you need to add Mockito to your project. Here’s how you can do it using Maven or Gradle.
Using Maven
Add the following dependencies to your pom.xml
file:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.3</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.12.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.12.0</version>
<scope>test</scope>
</dependency>
Using Gradle
Add the following dependencies to your build.gradle
file:
dependencies {
testImplementation 'org.mockito:mockito-core:5.12.0'
testImplementation 'org.mockito:mockito-junit-jupiter:5.12.0'
testImplementation 'org.mockito:mockito-junit-jupiter:5.12.0'
}
Step 2: Create a Class to Test
Create a class that you want to test. In this example, we will use a Calculator
class with basic arithmetic operations.
Calculator.java
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public double multiply(double a, double b) {
return a * b;
}
public double divide(double a, double b) {
if (b == 0) {
throw new IllegalArgumentException("Division by zero");
}
return a / b;
}
}
Step 3: Create a Test Class
Create a test class where you will create mocks and write your tests.
Using mock() Method
In this example, we will see how to create a mock object using the mock()
method.
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorTest {
@Test
void testCreateMock_Add() {
// Create a mock object of the Calculator class
Calculator calculator = mock(Calculator.class);
// Stub the add method
when(calculator.add(2, 3)).thenReturn(5);
// Use the mock object
int result = calculator.add(2, 3);
// Assert the result
assertEquals(5, result);
// Verify the interaction
verify(calculator).add(2, 3);
}
@Test
void testCreateMock_Subtract() {
// Create a mock object of the Calculator class
Calculator calculator = mock(Calculator.class);
// Stub the subtract method
when(calculator.subtract(3, 2)).thenReturn(1);
// Use the mock object
int result = calculator.subtract(3, 2);
// Assert the result
assertEquals(1, result);
// Verify the interaction
verify(calculator).subtract(3, 2);
}
}
Explanation of CalculatorTest
- Creating a Mock:
Calculator calculator = mock(Calculator.class);
This line creates a mock object of the
Calculator
class using themock()
method. - Stubbing a Method:
when(calculator.add(2, 3)).thenReturn(5);
This line defines the behavior of the
add
method. When theadd
method is called with arguments2
and3
, it will return5
. - Using the Mock Object:
int result = calculator.add(2, 3);
This line calls the
add
method on the mock object and stores the result. - Asserting the Result:
assertEquals(5, result);
This line checks if the result is
5
. - Verifying Interactions:
verify(calculator).add(2, 3);
This line verifies that the
add
method was called with arguments2
and3
.
Running the Tests using IntelliJ IDEA
- Run Tests: Right-click on the test class file and select
Run 'CalculatorTest'
. - View Results: The results will be displayed in the Run window, showing the test execution.
Using @Mock Annotation
In this example, we will see how to create a mock object using the @Mock
method.
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
public class CalculatorAnnotationTest {
@Mock
private Calculator calculator;
@BeforeEach
void setUp() {
// No need to initialize mocks manually
}
@Test
void testAdd_WithMockAnnotation() {
// Stub the add method
when(calculator.add(2, 3)).thenReturn(5);
// Use the mock object
int result = calculator.add(2, 3);
// Assert the result
assertEquals(5, result);
// Verify the interaction
verify(calculator).add(2, 3);
}
@Test
void testSubtract_WithMockAnnotation() {
// Stub the subtract method
when(calculator.subtract(3, 2)).thenReturn(1);
// Use the mock object
int result = calculator.subtract(3, 2);
// Assert the result
assertEquals(1, result);
// Verify the interaction
verify(calculator).subtract(3, 2);
}
}
Explanation of CalculatorAnnotationTest
- Creating a Mock Using
@Mock
Annotation:@Mock private Calculator calculator;
This annotation creates a mock object of the
Calculator
class. When used with@ExtendWith(MockitoExtension.class)
, Mockito initializes the mocks automatically. - Stubbing a Method:
when(calculator.add(2, 3)).thenReturn(5);
This line defines the behavior of the
add
method. When theadd
method is called with arguments2
and3
, it will return5
. - Using the Mock Object:
int result = calculator.add(2, 3);
This line calls the
add
method on the mock object and stores the result. - Asserting the Result:
assertEquals(5, result);
This line checks if the result is
5
. - Verifying Interactions:
verify(calculator).add(2, 3);
This line verifies that the
add
method was called with arguments2
and3
.
Running the Tests
You can run your tests using an IDE like IntelliJ IDEA or Eclipse or a build tool like Maven or Gradle.
Using IntelliJ IDEA
- Run Tests: Right-click on the test class file and select
Run 'CalculatorTest'
. - View Results: The results will be displayed in the Run window, showing the test execution.
Conclusion
Creating mocks with Mockito is straightforward. By following the steps outlined in this chapter, you can easily create mock objects, stub methods, and verify interactions in your tests using both the mock()
method and the @Mock
annotation. This will help you write more effective and maintainable unit tests.