I have three very simple classes. One of them extends parent class.
public class Parent{
protected String print() {
// some code
}
}
Here is a child class.
public class Child extends Parent {
/**
* Shouldn't invoke protected Parent.print() of parent class.
*/
@Override
protected String print() {
// some additional behavior
return super.print();
}
}
And test class.
public class ChildTest {
@Test
public void should_mock_invocation_of_protected_method_of_parent_class() throws Exception {
// Given
Child child = PowerMockito.mock(Child.class);
Method method = PowerMockito.method(Parent.class, "print");
PowerMockito.when(child, method).withNoArguments().thenReturn("abc");
// When
String retrieved = child.print();
// Than
Mockito.verify(child, times(1)).print(); // verification of child method
Assert.assertEquals(retrieved, "abc");
}
}
I need to verify super.print()
invocation. How can I do it?
3. Use of super() to access superclass constructor. As we know, when an object of a class is created, its default constructor is automatically called. To explicitly call the superclass constructor from the subclass constructor, we use super() .
We can use super. method() in a Child method to call Parent method.
This is a long time ago question, but here is how i did it, using Mockito spy, create a method which call the parent method in the child class:
public class Child extends Parent {
/**
* Shouldn't invoke protected Parent.print() of parent class.
*/
@Override
protected String print() {
// some additional behavior
return callParent();
}
protected callParent()
{
super.print();
}
}
And in the test :
@Test
public void sould_mock_invocation_of_protected_method_of_parent_class() throws Exception {
// Given
Child child = Mockito.spy(new Child());
Mockito.doReturn(null)
.when(child)
.callParent();
// When
String retrieved = child.print();
// Then
Mockito.verify(child, times(1)).callParent(); // verification of child method
Assert.assertEquals(retrieved, "abc");
}
Note: this test only check we call the parent method in the child class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With