How is Spy different from Mock in Mockito?

QuestionsQuestions8 SkillsProSpy in MockitoSep, 26 2025
0155

In Mockito, the key differences between a Spy and a Mock are as follows:

  1. Method Behavior:

    • Mock: All methods return default values (null, 0, false) unless explicitly stubbed.
    • Spy: Methods call the real implementation unless stubbed.
  2. Object State:

    • Mock: Operations do not change the state (e.g., adding to a mock list does not actually add anything).
    • Spy: Operations change the object's state just like a real object.
  3. Creation:

    • Mock: Created from a class, not an instance (e.g., Mockito.mock(ArrayList.class)).
    • Spy: Usually created from an instance (e.g., Mockito.spy(new ArrayList<>())).
  4. Use Cases:

    • Mock: When you want to completely control the behavior and do not need real methods.
    • Spy: When you want to use real methods but need to override only some behaviors.

These differences help you choose the right tool for your testing needs based on the specific requirements of your tests.

0 Comments

no data
Be the first to share your comment!