Mockito in Java
Mockito is the most widely used mocking library for Java. It creates fake versions of the classes your code depends on, such as a payment gateway, a database repository or an email sender, so you can test one class in isolation without touching real systems.
This lesson covers Mockito in Java from the start: adding it to a JUnit 6 project, creating mocks, stubbing return values with when().thenReturn(), throwing exceptions, verifying calls with verify(), argument matchers, the @Mock and @InjectMocks annotations, and strict stubbing. It ends with a full test for a checkout service. You should already know Java JUnit Basics and JUnit Assertions.
Why Mock Objects Are Needed
Most real classes depend on other classes. Consider an order service that charges a card and sends an email:
public interface PaymentGateway {
boolean charge(String customerId, long amountInPaise);
}
public interface EmailSender {
void send(String to, String subject);
}
public class OrderService {
private final PaymentGateway paymentGateway;
private final EmailSender emailSender;
public OrderService(PaymentGateway paymentGateway, EmailSender emailSender) {
this.paymentGateway = paymentGateway;
this.emailSender = emailSender;
}
public String placeOrder(String customerId, String email, long amountInPaise) {
boolean paid = paymentGateway.charge(customerId, amountInPaise);
if (!paid) {
return "PAYMENT_FAILED";
}
emailSender.send(email, "Order confirmed");
return "CONFIRMED";
}
}
Testing OrderService with the real PaymentGateway would charge a real card on every test run. The real EmailSender would send real emails. Both are slow, need network access and cost money.
| Problem with real dependencies | How a mock solves it |
|---|---|
| Real payments, emails or database writes | The mock does nothing real |
| Slow network calls | The mock answers instantly |
| Hard to force errors such as "card declined" | You tell the mock to return false or throw |
| Hard to know whether a call happened | Mockito records every call for verify() |
A mock is an object that implements the same type as the real dependency, returns whatever values you choose, and remembers how it was called.
Add Mockito to a Maven Project
Add mockito-core for the API and mockito-junit-jupiter for the JUnit extension, both with test scope, next to the JUnit dependency:
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>6.1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.23.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.23.0</version>
<scope>test</scope>
</dependency>
</dependencies>
On Java 21 and newer, Mockito prints a warning that it is "self-attaching" its Java agent, which future JDKs will block. Register Mockito as an agent in Surefire to remove the warning:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>properties</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
<configuration>
<argLine>-javaagent:${org.mockito:mockito-core:jar}</argLine>
</configuration>
</plugin>
</plugins>
</build>
How it works:
- The
propertiesgoal of the dependency plugin creates a property for every dependency's JAR path, such as${org.mockito:mockito-core:jar}. - Surefire passes that path to the test JVM with
-javaagent, so Mockito's inline mock maker loads at startup instead of attaching itself later. - For Gradle, the equivalent is adding the
mockito-coreJAR tojvmArgsof thetesttask as-javaagent.
Note: Mockito 5 uses the inline mock maker by default, so it can mock final classes and final methods without extra configuration.
Create a Mock With mock()
Mockito.mock(Type.class) creates a mock. Until you tell it otherwise, every method returns a default "empty" value.
import static org.mockito.Mockito.mock;
import java.util.List;
import java.util.Optional;
public class DefaultValuesDemo {
interface CourseRepository {
String findTitle(String id);
int countStudents(String id);
boolean exists(String id);
List<String> findAllIds();
Optional<String> findInstructor(String id);
}
public static void main(String[] args) {
CourseRepository repository = mock(CourseRepository.class);
System.out.println("findTitle: " + repository.findTitle("JAVA101"));
System.out.println("countStudents: " + repository.countStudents("JAVA101"));
System.out.println("exists: " + repository.exists("JAVA101"));
System.out.println("findAllIds: " + repository.findAllIds());
System.out.println("findInstructor: " + repository.findInstructor("JAVA101"));
}
}
Output:
findTitle: null
countStudents: 0
exists: false
findAllIds: []
findInstructor: Optional.empty
How it works:
mock(CourseRepository.class)creates an object that implementsCourseRepositorywithout any real code behind it.- Methods return
nullfor objects,0for numbers,falsefor booleans, and empty collections,Optionals and streams instead ofnull. - Nothing has been stubbed yet. The next sections show how to choose the return values.
Stub Return Values With when().thenReturn()
Stubbing tells a mock what to return for a specific call. The syntax reads like a sentence: "when this method is called with these arguments, then return this value".
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
class OrderServiceStubTest {
@Test
void successfulPaymentConfirmsOrder() {
PaymentGateway gateway = mock(PaymentGateway.class);
EmailSender emailSender = mock(EmailSender.class);
when(gateway.charge("CUST-1", 49_900)).thenReturn(true);
OrderService service = new OrderService(gateway, emailSender);
assertEquals("CONFIRMED", service.placeOrder("CUST-1", "asha@example.com", 49_900));
}
@Test
void declinedPaymentFailsOrder() {
PaymentGateway gateway = mock(PaymentGateway.class);
EmailSender emailSender = mock(EmailSender.class);
when(gateway.charge("CUST-2", 129_900)).thenReturn(false);
OrderService service = new OrderService(gateway, emailSender);
assertEquals("PAYMENT_FAILED", service.placeOrder("CUST-2", "ravi@example.com", 129_900));
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
when(gateway.charge("CUST-1", 49_900)).thenReturn(true)makes that exact call returntrue.- The second test forces a declined payment, which would be hard to arrange with a real bank.
- A call with different arguments, such as
charge("CUST-9", 100), still returns the defaultfalse.
Return Different Values on Consecutive Calls
thenReturn can take several values. Each call returns the next one, and the last value repeats.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
class ConsecutiveCallsTest {
interface OtpService {
String nextOtp();
}
@Test
void returnsValuesInOrder() {
OtpService otpService = mock(OtpService.class);
when(otpService.nextOtp()).thenReturn("111111", "222222", "333333");
assertEquals("111111", otpService.nextOtp());
assertEquals("222222", otpService.nextOtp());
assertEquals("333333", otpService.nextOtp());
assertEquals("333333", otpService.nextOtp()); // last value repeats
}
}
This test passes. Consecutive stubbing is useful for testing retries, where the first call fails and a later one succeeds.
Throw Exceptions With thenThrow and doThrow
Mocks make it easy to test error handling. Use thenThrow for methods that return a value and doThrow().when(mock) for void methods.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
class ExceptionStubbingTest {
@Test
void gatewayTimeoutIsPropagated() {
PaymentGateway gateway = mock(PaymentGateway.class);
when(gateway.charge("CUST-1", 49_900))
.thenThrow(new IllegalStateException("Gateway timeout"));
OrderService service = new OrderService(gateway, mock(EmailSender.class));
IllegalStateException error = assertThrows(IllegalStateException.class,
() -> service.placeOrder("CUST-1", "asha@example.com", 49_900));
assertEquals("Gateway timeout", error.getMessage());
}
@Test
void emailFailureAfterPayment() {
PaymentGateway gateway = mock(PaymentGateway.class);
EmailSender emailSender = mock(EmailSender.class);
when(gateway.charge("CUST-1", 49_900)).thenReturn(true);
doThrow(new RuntimeException("SMTP server down"))
.when(emailSender).send(anyString(), anyString());
OrderService service = new OrderService(gateway, emailSender);
assertThrows(RuntimeException.class,
() -> service.placeOrder("CUST-1", "asha@example.com", 49_900));
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
thenThrowmakes the stubbed call throw the given exception instead of returning a value.when(emailSender.send(...))does not compile, becausesendreturnsvoidand there is nothing to pass towhen. ThedoThrow(...).when(emailSender).send(...)form puts the mock first, which works for any method.- The second test reveals a real design question: the customer has paid but gets an exception. The checkout example at the end of this lesson handles that case properly.
Verify Method Calls With verify()
Stubbing controls what a mock returns. Verification checks what your code did with the mock: which methods it called, with which arguments, and how many times.
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
class OrderServiceVerifyTest {
@Test
void confirmedOrderSendsOneEmail() {
PaymentGateway gateway = mock(PaymentGateway.class);
EmailSender emailSender = mock(EmailSender.class);
when(gateway.charge("CUST-1", 49_900)).thenReturn(true);
new OrderService(gateway, emailSender).placeOrder("CUST-1", "asha@example.com", 49_900);
verify(gateway).charge("CUST-1", 49_900);
verify(emailSender, times(1)).send("asha@example.com", "Order confirmed");
}
@Test
void failedPaymentSendsNoEmail() {
PaymentGateway gateway = mock(PaymentGateway.class);
EmailSender emailSender = mock(EmailSender.class);
when(gateway.charge("CUST-2", 129_900)).thenReturn(false);
new OrderService(gateway, emailSender).placeOrder("CUST-2", "ravi@example.com", 129_900);
verify(emailSender, never()).send(anyString(), anyString());
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
If the service forgot to send the email, the first test would fail with:
Wanted but not invoked:
emailSender.send(
"asha@example.com",
"Order confirmed"
);
-> at com.gocourse.OrderServiceVerifyTest.confirmedOrderSendsOneEmail(OrderServiceVerifyTest.java:22)
Actually, there were zero interactions with this mock.
How it works:
verify(gateway).charge(...)is short forverify(gateway, times(1)). It fails unless that exact call happened exactly once.never()checks that a call did not happen, which is often the most important check in a failure path.- The failure message shows the expected call and what actually happened, so you can see the bug without a debugger.
| Verification mode | Passes when the call happened |
|---|---|
times(n) | Exactly n times |
never() | Zero times |
atLeastOnce() | One or more times |
atLeast(n) / atMost(n) | At least / at most n times |
only() | Exactly once, and no other method on that mock was called |
Two more helpers check the whole mock: verifyNoInteractions(mock) passes only if the mock was never used, and verifyNoMoreInteractions(mock) fails if any call was not already verified.
Use Argument Matchers
Sometimes the exact argument does not matter, or you cannot know it in advance. Argument matchers such as any() and anyString() match a range of values in both when and verify.
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.longThat;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
class ArgumentMatchersTest {
@Test
void anyAmountIsApprovedForVipCustomers() {
PaymentGateway gateway = mock(PaymentGateway.class);
when(gateway.charge(startsWith("VIP-"), anyLong())).thenReturn(true);
assertTrue(gateway.charge("VIP-7", 1_000_000));
assertTrue(gateway.charge("VIP-99", 100));
assertFalse(gateway.charge("CUST-1", 100)); // not stubbed: default false
}
@Test
void verifiesAmountWithACustomCondition() {
PaymentGateway gateway = mock(PaymentGateway.class);
gateway.charge("CUST-1", 75_000);
verify(gateway).charge(eq("CUST-1"), longThat(amount -> amount > 50_000 && amount < 100_000));
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
startsWith("VIP-")matches any string with that prefix, andanyLong()matches anylong.longThattakes a lambda and matches when it returnstrue. For object parameters, useargThat; for primitive parameters, use the typed versionsintThat,longThatand so on, becauseargThatreturnsnulland would cause aNullPointerExceptionwhen unboxed.eq("CUST-1")wraps a plain value as a matcher. It is needed here because of the rule below.
| Matcher | Matches |
|---|---|
any() / any(Type.class) | Any value (the typed version excludes null) |
anyString(), anyInt(), anyLong(), anyList() | Any non-null value of that type |
eq(value) | A value equal to value |
isNull() / notNull() | null / not null |
startsWith, endsWith, contains | Strings with that text |
argThat(predicate) / longThat(predicate) | Values for which the lambda returns true (use the typed form for primitives) |
Note: If one argument uses a matcher, all arguments of that call must use matchers.
verify(gateway).charge("CUST-1", anyLong())throwsInvalidUseOfMatchersExceptionwith the message "2 matchers expected, 1 recorded". Writeeq("CUST-1")instead.
Use @Mock and @InjectMocks
Creating mocks by hand in every test gets repetitive. With the MockitoExtension, you declare mocks as fields with @Mock, and @InjectMocks creates the class under test with those mocks passed in.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class OrderServiceAnnotationTest {
@Mock
PaymentGateway gateway;
@Mock
EmailSender emailSender;
@InjectMocks
OrderService service;
@Test
void confirmsPaidOrder() {
when(gateway.charge("CUST-1", 49_900)).thenReturn(true);
assertEquals("CONFIRMED", service.placeOrder("CUST-1", "asha@example.com", 49_900));
verify(emailSender).send("asha@example.com", "Order confirmed");
}
@Test
void doesNotEmailWhenPaymentFails() {
when(gateway.charge("CUST-2", 129_900)).thenReturn(false);
assertEquals("PAYMENT_FAILED", service.placeOrder("CUST-2", "ravi@example.com", 129_900));
verifyNoInteractions(emailSender);
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
@ExtendWith(MockitoExtension.class)lets Mockito process the annotations before each test.- Each
@Mockfield gets a new mock for every test, just like a@BeforeEachfixture from JUnit Test Fixtures. @InjectMockscalls the biggest constructor ofOrderServiceand passes the mocks whose types match its parameters.verifyNoInteractions(emailSender)confirms the email sender was never touched when payment failed.
Strict Stubbing and UnnecessaryStubbingException
MockitoExtension uses strict stubs by default. If a test stubs a method that the code never calls, the test fails. This catches tests that no longer check what they claim to check.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class StrictStubsTest {
@Mock
PaymentGateway gateway;
@Mock
EmailSender emailSender;
@InjectMocks
OrderService service;
@Test
void stubbedWithWrongAmount() {
when(gateway.charge("CUST-1", 49_900)).thenReturn(true); // never used
// the code charges 59_900, so the stub above does not match
assertEquals("PAYMENT_FAILED", service.placeOrder("CUST-1", "asha@example.com", 59_900));
}
}
Output:
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'charge' method:
gateway.charge("CUST-1", 59900L);
-> at com.gocourse.OrderService.placeOrder(OrderService.java:12)
- has following stubbing(s) with different arguments:
1. gateway.charge("CUST-1", 49900L);
-> at com.gocourse.StrictStubsTest.stubbedWithWrongAmount(StrictStubsTest.java:23)
How it works:
- The test stubs
chargefor 49,900 paise, but the code calls it with 59,900. Without strictness, the mock would quietly returnfalse, and the test would pass for the wrong reason. - Mockito notices that a stubbed method was called with different arguments and fails immediately with
PotentialStubbingProblem. - A stub that is never called at all fails with
UnnecessaryStubbingExceptionat the end of the test. - When a stub is intentionally optional, mark it with
lenient().when(...).
Real-World Example: Mockito in Java for a Checkout Service
This checkout service reserves stock, charges the customer, and sends a confirmation. If payment fails, it releases the stock. If the email fails after payment, the order is still confirmed and the failure is logged for a retry.
package com.gocourse.checkout;
public interface InventoryService {
boolean reserve(String sku, int quantity);
void release(String sku, int quantity);
}
package com.gocourse.checkout;
public interface PaymentGateway {
boolean charge(String customerId, long amountInPaise);
}
package com.gocourse.checkout;
public interface Notifier {
void orderConfirmed(String customerId, String sku);
void retryLater(String customerId, String reason);
}
package com.gocourse.checkout;
public class CheckoutService {
public enum Result { CONFIRMED, OUT_OF_STOCK, PAYMENT_DECLINED }
private final InventoryService inventory;
private final PaymentGateway payments;
private final Notifier notifier;
public CheckoutService(InventoryService inventory, PaymentGateway payments, Notifier notifier) {
this.inventory = inventory;
this.payments = payments;
this.notifier = notifier;
}
public Result checkout(String customerId, String sku, int quantity, long unitPriceInPaise) {
if (!inventory.reserve(sku, quantity)) {
return Result.OUT_OF_STOCK;
}
if (!payments.charge(customerId, unitPriceInPaise * quantity)) {
inventory.release(sku, quantity);
return Result.PAYMENT_DECLINED;
}
try {
notifier.orderConfirmed(customerId, sku);
} catch (RuntimeException e) {
notifier.retryLater(customerId, e.getMessage());
}
return Result.CONFIRMED;
}
}
package com.gocourse.checkout;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.gocourse.checkout.CheckoutService.Result;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
@DisplayName("CheckoutService")
class CheckoutServiceTest {
@Mock InventoryService inventory;
@Mock PaymentGateway payments;
@Mock Notifier notifier;
@InjectMocks CheckoutService checkout;
@Test
@DisplayName("confirms the order when stock and payment succeed")
void happyPath() {
when(inventory.reserve("BK-1", 2)).thenReturn(true);
when(payments.charge("CUST-1", 99_800)).thenReturn(true);
Result result = checkout.checkout("CUST-1", "BK-1", 2, 49_900);
assertEquals(Result.CONFIRMED, result);
verify(notifier).orderConfirmed("CUST-1", "BK-1");
verify(inventory, never()).release(anyString(), anyInt());
}
@Test
@DisplayName("stops before charging when the item is out of stock")
void outOfStock() {
when(inventory.reserve("KB-7", 1)).thenReturn(false);
assertEquals(Result.OUT_OF_STOCK, checkout.checkout("CUST-1", "KB-7", 1, 129_900));
verifyNoInteractions(payments, notifier);
}
@Test
@DisplayName("releases reserved stock when payment is declined")
void paymentDeclined() {
when(inventory.reserve("BK-1", 3)).thenReturn(true);
when(payments.charge(anyString(), anyLong())).thenReturn(false);
assertEquals(Result.PAYMENT_DECLINED, checkout.checkout("CUST-2", "BK-1", 3, 49_900));
verify(inventory).release("BK-1", 3);
verifyNoInteractions(notifier);
}
@Test
@DisplayName("still confirms the order and schedules a retry when the email fails")
void notificationFailure() {
when(inventory.reserve("BK-1", 1)).thenReturn(true);
when(payments.charge("CUST-3", 49_900)).thenReturn(true);
doThrow(new RuntimeException("SMTP server down"))
.when(notifier).orderConfirmed("CUST-3", "BK-1");
assertEquals(Result.CONFIRMED, checkout.checkout("CUST-3", "BK-1", 1, 49_900));
verify(notifier).orderConfirmed("CUST-3", "BK-1");
verify(notifier).retryLater("CUST-3", "SMTP server down");
verifyNoMoreInteractions(notifier);
}
}
Output in the Console Launcher:
└─ CheckoutService ✔
├─ confirms the order when stock and payment succeed ✔
├─ stops before charging when the item is out of stock ✔
├─ releases reserved stock when payment is declined ✔
└─ still confirms the order and schedules a retry when the email fails ✔
[ 4 tests successful ]
[ 0 tests failed ]
How it works:
- No real systems. All three dependencies are interfaces, and
@Mockreplaces each one. The tests run in milliseconds and never touch a warehouse, a bank or a mail server. - Correct amount.
happyPathstubscharge("CUST-1", 99_800). Strict stubbing guarantees the service really calculated 2 × 49,900; any other amount would fail the test. - Early exit.
outOfStockusesverifyNoInteractions(payments, notifier)to prove the customer is never charged for an item that is not available. - Compensation.
paymentDeclinedverifies that the reserved stock is released, which prevents items from being locked forever. - Partial failure.
notificationFailureusesdoThrowon avoidmethod to simulate a mail outage, then checks that the order is still confirmed and a retry is scheduled.verifyNoMoreInteractions(notifier)makes sure nothing else was sent.
The next lesson, Java Mock Objects, goes further with spies, argument captors, custom answers and call-order checks.