In Mockito, you cannot directly verify if a method of a superclass was called. Mockito works with mocks and spies to verify interactions with specific methods, but it doesn't have built-in support for verifying calls to superclass methods.
However, you can address this by spying on the subclass and checking if the superclass method is called from there. Below is an example of how to achieve this using Mockito.spy
:
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
// Superclass
class Parent {
void someMethod() {
System.out.println("Parent's method called");
}
}
// Subclass
class Child extends Parent {
@Override
void someMethod() {
super.someMethod(); // Calls the superclass method
System.out.println("Child's method called");
}
}
public class SuperclassMethodTest {
@Test
void testSuperclassMethodCalled() {
// Create a spy of the Child class
Child childSpy = spy(new Child());
// Call the method
childSpy.someMethod();
// Verify if the method from the Parent (superclass) was called
verify(childSpy).someMethod(); // Verifies the method in the spy (subclass)
// Note: You cannot directly verify calls to `super.someMethod()`
// but you can confirm it was triggered from the subclass method.
}
}
Key Points
- Spy the subclass: Use
spy()
to create a spy instance of the subclass. - Superclass Method Indirect Verification: While you cannot directly verify
super.someMethod()
, the verification ofsomeMethod()
in the subclass ensures the invocation, assuming you know the subclass delegates to the superclass. - Alternative Approach: For more control, you can introduce hooks in your subclass specifically for testing, or extract common behavior to separate components that can be mocked and verified directly.
If you need detailed testing of superclass behavior in isolation, consider writing unit tests specifically for the superclass.