Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify invocation of super.method() of parent class?

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?

like image 850
Aaron Avatar asked Jul 22 '14 19:07

Aaron


People also ask

How do I access the superclass method?

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() .

Can you call a parent class method from child class object?

We can use super. method() in a Child method to call Parent method.


1 Answers

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

like image 69
Geof Avatar answered Oct 12 '22 23:10

Geof