Sobes.tech
Junior — Middle

Can you explain the differences between Mock and Spy in Mockito and when to use them?

sobes.tech AI

Answer from AI

In Mockito:

  • Mock is a fully simulated object, where all methods do nothing by default or return default values. Its behavior is manually configured.
  • Spy is a partially simulated object that wraps a real object. By default, it calls real methods, but the behavior of individual methods can be overridden.

When to use:

  • Mock — when you need to completely isolate the class under test from dependencies and control all calls.
  • Spy — when you need to test a real object but want to replace the behavior of some methods (for example, to avoid side effects).

Example:

List<String> list = new ArrayList<>();
List<String> spyList = Mockito.spy(list);

Mockito.doReturn("mocked").when(spyList).get(0);

System.out.println(spyList.get(0)); // Will output "mocked"
System.out.println(spyList.size()); // Calls the real size() method, returns 0

Using a spy is useful when you want to verify interactions with a real object but control part of its behavior.

Can you explain the differences between Mock and Spy… - sobes.tech