Featured Article

Master Mockito Tutorial Java: A Comprehensive Guide to Mocking

Kenneth Jul 13, 2026

Mockito is a popular Java framework used to write unit tests for your Java applications. It makes it easy to test your code with mock objects, allowing you to isolate your system under test and substitute any dependent resources, like databases or web services, with mocks that simulate their behavior. This comprehensive tutorial will guide you through the basics of Mockito, starting from its installation to creating complex mock behaviors.

10 Best Websites to Learn Java for Free in 2026
10 Best Websites to Learn Java for Free in 2026

Before we dive in, make sure you have the Java Development Kit (JDK) installed, along with a testing framework like JUnit andAssertJ for better assertions. In this tutorial, we'll use Mockito version 3.x.

Coffee Mojito 🍸
Coffee Mojito 🍸

Getting Started with Mockito

First, add the Mockito dependency to your project. If you're using Maven, add this to your pom.xml:

JAVA MAIN METHOD
JAVA MAIN METHOD

```xml org.mockito mockito-core 3.6.28 test ```

For Gradle, add this to your build file:

```java testImplementation 'org.mockito:mockito-core:3.6.28' ```

Creating Simple Mocks

How To Convert Excel Data Into List Of Java Objects : Poiji API
How To Convert Excel Data Into List Of Java Objects : Poiji API

Mockito allows you to create mocks of interfaces and abstract classes. Here's how to create a simple mock:

```java // Import Mockito's static import for creating mocks import static org.mockito.Mockito.mock; // Create a mock of the interface Car Car car = mock(Car.class); ```

Now, let's explore some of Mockito's basic features.

Verifying Interactions

Eventos en Java. Ventanas
Eventos en Java. Ventanas

Mockito verifies interactions between your system under test and the mocks. You can check if a method was called on a mock with:

```java // Use Mockito's verify method verify(car femenStart()); ```

To verify multiple interactions, use the verifyΩ…Ω‡times() method:

```java verify(car, times(2)).start(); ```

Stubs and Answer Methods

a laptop computer sitting on top of a desk with the title 5 youtubee channels to learn
a laptop computer sitting on top of a desk with the title 5 youtubee channels to learn

Mockito allows you to create mocks with pre-programmed behaviors, called stubs. You can define how a method should behave using the when() method:

```java when(car.getSpeed()).thenReturn(120); ```

You can also use answer methods to return values based on the method's input or call the real implementation of a method:

a computer screen with different types of text and numbers on it, including the font bar
a computer screen with different types of text and numbers on it, including the font bar
80+ Pattern Programs In Java
80+ Pattern Programs In Java
an image of a computer screen with the words movable and astralct method
an image of a computer screen with the words movable and astralct method
πŸ“š Java Quick Revision Notes Aesthetic Edition
πŸ“š Java Quick Revision Notes Aesthetic Edition
How to Become a Java Developer (Step-by-Step)
How to Become a Java Developer (Step-by-Step)
Java Project Ideas For Practice πŸ”₯πŸš€
Java Project Ideas For Practice πŸ”₯πŸš€
Top 10 Design Patterns for Programming Interviews
Top 10 Design Patterns for Programming Interviews
How To Download Java Minecraft And Install The Launcher
How To Download Java Minecraft And Install The Launcher
πŸš€ The Ultimate Guide to Java Method Overloading 🎯
πŸš€ The Ultimate Guide to Java Method Overloading 🎯

```java when(car.calcSpeed(times(1))).thenAnswer(invocation -> invocation.getArguments()[0] * 2); ```

Capturing Arguments

To capture arguments passed to a stubbed method, use the Answer interface:

```java Answer answer = new Answer() { @Override public String answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); return args[0] + " captured"; } }; when(car.getGreeting(name)).thenAnswer(answer); ```

InOrder Verification

Mockito allows you to verify the order of method calls on a mock with inOrder():

```java InOrder inOrder = Mockito.inOrder(car); // Verify the order of method calls inOrder.verify(car).start(); inOrder.verify(car).stop(); ```

Creating Complex Mock Behaviors

Mockito allows you to create complex mock behaviors using Spy, doReturn, and doThrow.

Spy

A spy is a partially mock tod an object that has real and mocked methods. Create a spy like this:

```java Car car = spy(RealCar.class); ```

Then, stub the methods as needed:

```java when(car.start()).thenReturn("Engine started"); ```

doReturn and doThrow

Use doReturn and doThrow to specify the return value or exception when invoking a method:

```java doReturn("Hello, world!").when(car).greet(); doThrow(UnsupportedOperationException.class).when(car).stop(); ```

Advanced Mockito Features

In this section, we'll explore some advanced features like argument matchers, repeating behaviors, and time-based verifications.

Argument Matchers

Mockito provides several argument matchers to match any argument value. Here are a few examples:

```java // Any argument anyString(); // Null arguments isNull(); // Arguments of specific types eq("expected value"); // Using matchers with verify verify(car, never()).start(anyBoolean(), anyInt(), eq("expected")); ```

Repeating Behaviors

Use the given method to define repeating behaviors for a mock:

```java given(car.getSpeed()).willReturn(100).willReturn(120).willReturn(130); ```

Time-based Verifications

Verify method calls within a specific timeframe using within():

```java verify(car, within(100).milliseconds()).start(); ```

With this comprehensive tutorial, you now have a solid understanding of Mockito and its features. Happy testing!