Home > Java > javaTutorial > How to Mock Only a Specific Method Call in a Superclass with Mockito?

How to Mock Only a Specific Method Call in a Superclass with Mockito?

Patricia Arquette
Release: 2024-10-31 06:17:02
Original
1081 people have browsed it

How to Mock Only a Specific Method Call in a Superclass with Mockito?

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>
Copy after login

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>
Copy after login

Explanation:

  1. Create an instance of the ChildService class using Mockito's spy() method. This creates a spy object that can be used to selectively mock methods.
  2. Stub the method in the superclass that you don't want to mock. This is done using Mockito.doNothing(). In the example, the validate() method in the superclass is stubbed.
  3. Perform the action on the spy object (in this case, calling save()).
  4. Verify that the specific method call was made on the spy object (in this case, load() is verified).

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template