简体   繁体   中英

How can I mock protected method of parent class?

I try to mock protected method of the parent class. For that reason I use Mockito & 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 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 I'm doing wrong?

If you want to check the foo() method is really called, you dont't need neither Mockito, nor PowerMockito.

Catching the runtime exception informs you that 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();
    }
}

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM