How can I fake a protected method of a parent class?

I am trying to make fun of the protected method of the parent class. For this reason, I use Mockitoand PowerMockito. My parent class.

public class Parent {
    protected int foo() {
        throw new RuntimeException("Do not invoke this method.");
    }
}

My child class.

public class Child extends Parent {
    protected int boo() {
        return super.foo();
    }
}

And a test class.

@RunWith(PowerMockRunner.class)
@PrepareForTest({Parent.class, Child.class})
public class ChildTest {

    @Mock
    private Child childMock;

    @Before
    public void before() {
        initMocks(childMock);
    }

    @Test
    public void shouldInvokeProtectedMockedMethod() throws Exception {
        /* Given */
        PowerMockito.doReturn(500).when(childMock, "foo");
        /* When */
        childMock.boo();
        /* Then */
        Mockito.verify(childMock, Mockito.times(1)).boo();
        Mockito.verify(childMock, Mockito.times(1)).foo();
    }

    @After
    public void after() {
        Mockito.reset(childMock);
    }
}

When I run it, I get this error

Wanted but not invoked:
child.foo();
-> at com.test.ChildTest.shouldInvokeProtectedMockedMethod(ChildTest.java:36)

However, there were other interactions with this mock:
child.boo();
-> at com.test.ChildTest.shouldInvokeProtectedMockedMethod(ChildTest.java:33)

What am I doing wrong?

+4
source share
2 answers

If you want to check if the foo () method is actually called, you do not need either Mockito or PowerMockito.

Capturing a runtime exception informs you that the foo () method has been called.

package foo.bar;

import org.junit.Test;

public class ChildTest {

    /**
     * child.boo() calls super.foo(), then throws a RuntimeException.
     */
    @Test(expected = RuntimeException.class)
    public void shouldInvokeProtectedMethod() {
        Child child = new Child();
        child.boo();
    }
}
0
source

Try something like this:

@Test
public void shouldInvokeProtectedMockedMethod() throws Exception {
    int expected = 1;
    Child childMock = mock(Child.class);
    when(childMock.foo()).thenReturn(expected);
    when(childMock.boo()).thenCallRealMethod();

    childMock.boo();
    org.mockito.Mockito.verify(childMock, org.mockito.Mockito.times(1)).boo();
    org.mockito.Mockito.verify(childMock, org.mockito.Mockito.times(1)).foo();
}
0
source

Source: https://habr.com/ru/post/1589100/


All Articles