Java Mockito
In this page:
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 1 topics to unlock
0/1 topics done
Complete these topics first: