如何模拟父类的受保护方法?

时间:2015-05-21 00:53:32

标签: java mockito

我尝试模拟父类的受保护方法。出于这个原因,我使用Mockito& PowerMockito。我的父班。

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

我的孩子上课。

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

测试课。

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

当我运行它时,我收到此错误

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)

我做错了什么?

2 个答案:

答案 0 :(得分:0)

如果你想检查真正调用的foo()方法,你既不需要Mockito,也不需要PowerMockito。

捕获运行时异常会通知您已调用foo()方法。

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

答案 1 :(得分:0)

尝试这样的事情:

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