Mocking Only a Specific Method Call in Superclass with Mockito
When conducting unit tests using Mockito, it can be necessary to mock only a specific call to a method within a superclass while leaving other calls unaffected. Consider the following scenario:
<code class="java">class BaseService { public void save() {...} } public Childservice extends BaseService { public void save(){ //some code super.save(); } }</code>
In this example, you want to mock only the call to super.save() within the ChildService class, preserving the behavior of the other save() method call.
Solution Using Spying and Stubbing
While refactoring may be a viable solution, it is not always feasible. In such cases, you can leverage spying and stubbing techniques to achieve the desired mocking behavior:
<code class="java">@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>
Explanation:
By employing spying and stubbing, you can effectively simulate the desired mocking behavior, allowing you to test specific method calls within superclasses while preserving the original functionality.
The above is the detailed content of How to Mock Only a Specific Method Call in a Superclass with Mockito?. For more information, please follow other related articles on the PHP Chinese website!