Home >Java >javaTutorial >How to Mock a Method Call from a Superclass with Mockito: A Practical Guide
Overcoming Mockito Challenges: Mocking a Method Call from a Superclass
Mockito, a Java mocking framework, provides a powerful tool for isolating method calls during testing. However, certain scenarios require mocking only specific calls, particularly when dealing with inheritance.
Consider the following class hierarchy:
<code class="java">class BaseService { public void save() {...} } public Childservice extends BaseService { public void save(){ //some code super.save(); } } </code>
The goal is to mock only the call to super.save() in the ChildService class, leaving the original method invocation intact for the first call.
One approach involves strategically using Mockito's spy() method to create a mock of the ChildService class. By stubbing the validate() method of the BaseService class, which is called in super.save(), we effectively prevent the unwanted method call:
<code class="java">class BaseService { public void validate(){ fail(" I must not be called"); } public void save(){ //Save method of super will still be called. validate(); } } class ChildService extends BaseService{ public void load(){} public void save(){ super.save(); load(); } } @Test public void testSave() { ChildService classToTest = Mockito.spy(new ChildService()); // Prevent/stub logic in super.save() Mockito.doNothing().when((BaseService)classToTest).validate(); // When classToTest.save(); // Then verify(classToTest).load(); }</code>
This approach effectively isolates the call to super.save() while allowing the original method invocation for the first call. It ensures that the test focuses specifically on the desired method under scrutiny.
The above is the detailed content of How to Mock a Method Call from a Superclass with Mockito: A Practical Guide. For more information, please follow other related articles on the PHP Chinese website!