Mocking a Method in the Same Test Class Using Mockito Spy

Date: 2025-02-10
This article demonstrates using Mockito's spy()
method for partial mocking within a unit test. When testing a class with interdependent methods (e.g., calculateSquareSum()
calling add()
), spy()
allows mocking a specific method (add()
) without affecting others. A spy object is created using Mockito.spy()
, and the method to be mocked is stubbed using when(...).thenReturn(...)
. This enables isolated testing of individual methods, ensuring accurate and reliable unit tests. The example uses JUnit 5 and demonstrates verifying the expected outcome after mocking.
Read more: https://www.javacodegeeks.com/mockito-spy-mocking-a-method-in-the-same-class-example.html
Subscribe to my newsletter
Read articles from Yatin batra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
