Mockito in Java

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 254 of 306

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 dependenciesHow a mock solves it
Real payments, emails or database writesThe mock does nothing real
Slow network callsThe 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 happenedMockito 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 properties goal 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-core JAR to jvmArgs of the test task 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 implements CourseRepository without any real code behind it.
  • Methods return null for objects, 0 for numbers, false for booleans, and empty collections, Optionals and streams instead of null.
  • 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 return true.
  • 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 default false.

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:

  • thenThrow makes the stubbed call throw the given exception instead of returning a value.
  • when(emailSender.send(...)) does not compile, because send returns void and there is nothing to pass to when. The doThrow(...).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 for verify(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 modePasses 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, and anyLong() matches any long.
  • longThat takes a lambda and matches when it returns true. For object parameters, use argThat; for primitive parameters, use the typed versions intThat, longThat and so on, because argThat returns null and would cause a NullPointerException when unboxed.
  • eq("CUST-1") wraps a plain value as a matcher. It is needed here because of the rule below.
MatcherMatches
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, containsStrings 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()) throws InvalidUseOfMatchersException with the message "2 matchers expected, 1 recorded". Write eq("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 @Mock field gets a new mock for every test, just like a @BeforeEach fixture from JUnit Test Fixtures.
  • @InjectMocks calls the biggest constructor of OrderService and 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 charge for 49,900 paise, but the code calls it with 59,900. Without strictness, the mock would quietly return false, 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 UnnecessaryStubbingException at 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:

  1. No real systems. All three dependencies are interfaces, and @Mock replaces each one. The tests run in milliseconds and never touch a warehouse, a bank or a mail server.
  2. Correct amount. happyPath stubs charge("CUST-1", 99_800). Strict stubbing guarantees the service really calculated 2 × 49,900; any other amount would fail the test.
  3. Early exit. outOfStock uses verifyNoInteractions(payments, notifier) to prove the customer is never charged for an item that is not available.
  4. Compensation. paymentDeclined verifies that the reserved stock is released, which prevents items from being locked forever.
  5. Partial failure. notificationFailure uses doThrow on a void method 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Mockito in Java and get answers drawn from it.

Signed-in readers only.