Home > Java > javaTutorial > How to Mock Superclass Method Invocation in a Child Class?

How to Mock Superclass Method Invocation in a Child Class?

Mary-Kate Olsen
Release: 2024-11-04 05:51:01
Original
319 people have browsed it

How to Mock Superclass Method Invocation in a Child Class?

Mocking Superclass Method Invocation in Child Class

In unit testing, it is sometimes necessary to mock a method call within a subclass while leaving the original behavior intact in the superclass. This scenario can arise when testing methods that delegate to parent classes.

Consider the following example:

<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 case, a test requires mocking only the call to super.save() in the ChildService method while retaining the original behavior of the save() method in the BaseService class.

One approach to achieve this is by employing the spy functionality provided by Mockito. By spying on the ChildService instance, accessing the BaseService instance is possible, allowing for fine-grained control over the 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>
Copy after login

By mocking the validate() method in the BaseService class, the test ensures that the original logic in super.save() is not executed. Additionally, stubbing the load() method in the ChildService class verifies that it is called as expected. This approach provides fine-grained control over method invocations and allows for the isolation of specific functionality during testing.

The above is the detailed content of How to Mock Superclass Method Invocation in a Child Class?. 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