← Back to Advanced Java Course | Chapter 9: Testing | Lesson 1 of 1

Java Mockito

Creating Mock Objects

Mockito creates fake, controllable stand-ins for your real dependencies -- a mock database repository or a mock external API client, for example. This lets you test a class's own logic in isolation without actually hitting a database or network service during your test run.

Example: Creating Mock Objects

java
import static org.mockito.Mockito.*;
import java.util.List;
public class Main {
	public static void main(String[] args) {
		List<String> mockList = mock(List.class); // fake stand-in, no real implementation
		when(mockList.size()).thenReturn(10);
		System.out.println(mockList.size());
	}
}

Spying on Real Objects

Spies wrap a real object instead of replacing it entirely, so calls pass through to the real implementation by default. This lets you track which methods were actually invoked on a concrete instance while selectively stubbing just the specific methods you need different behavior from.

Example: Spying on Real Objects

java
import static org.mockito.Mockito.*;
import java.util.*;
public class Main {
	public static void main(String[] args) {
		List<String> realList = new ArrayList<>();
		List<String> spyList = spy(realList); // calls pass through by default
		spyList.add("real item");
		when(spyList.size()).thenReturn(100); // selectively stubbed
		System.out.println(spyList.size());
	}
}

Mocking Void Methods

Void methods don't return a value to assert against, but Mockito still lets you stub them -- to throw an exception when called, or to trigger a custom callback via doAnswer() -- and, critically, to verify afterward that they were actually invoked at all.

Example: Mocking Void Methods

java
import static org.mockito.Mockito.*;
public class Main {
	interface Logger { void log(String msg); }
	public static void main(String[] args) {
		Logger mockLogger = mock(Logger.class);
		doThrow(new RuntimeException("log failed")).when(mockLogger).log("error");
		try {
			mockLogger.log("error");
		} catch (RuntimeException e) {
			System.out.println("Caught: " + e.getMessage());
		}
		verify(mockLogger).log("error"); // confirms it was actually invoked
	}
}

Verifying Method Interactions

Beyond stubbing return values, Mockito lets you verify that a method was actually called and how many times, using verify(). It fails the test if the expected interaction never happened, which is essential for checking side effects like 'was a notification actually sent' that don't show up in a return value.

Example: Verifying Method Interactions

java
import static org.mockito.Mockito.*;
public class Main {
	interface EmailService { void send(String to); }
	public static void main(String[] args) {
		EmailService mockService = mock(EmailService.class);
		mockService.send("[email protected]");
		verify(mockService, times(1)).send("[email protected]"); // fails if never called
	}
}

Argument Matchers

Argument matchers like any() and eq() let you stub or verify a method call without pinning down the exact argument value passed in. They're especially useful when the real argument is something dynamic and unpredictable at test-write time, such as a generated ID or the current timestamp.

Example: Argument Matchers

java
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;
public class Main {
	interface Repo { String findById(int id); }
	public static void main(String[] args) {
		Repo mockRepo = mock(Repo.class);
		when(mockRepo.findById(anyInt())).thenReturn("found"); // matches any int argument
		System.out.println(mockRepo.findById(999));
	}
}
🔒

Chapter Quiz — Complete all 1 topics to unlock

0/1 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.