几天前发布了新版本的PowerMockito,并支持验证私有/受保护的方法调用。虽然我在简单的情况下使它工作,但我错过了一些具有更“复杂”功能的东西。鉴于以下类别:
public class A {
protected void myMethod(Exception... ex) {
System.out.println("Method A");
}
protected void another() {
System.out.println("Method A 1");
}
}
public class B extends A {
@Override
protected void myMethod(Exception... ex) {
System.out.println("Method B");
}
@Override
protected void another() {
System.out.println("Method B 1");
}
}
public class C extends B {
@Override
protected void myMethod(Exception... ex) {
System.out.println("Method C");
}
public void testMe() {
myMethod(new NullPointerException("XXX"));
}
@Override
protected void another() {
System.out.println("Method C 1");
}
public void testMeAnother() {
another();
}
}
以及以下测试用例:
@PrepareForTest({ A.class, B.class, C.class })
public class MethodTest {
@Test
public void test() throws Exception {
C classUnderTest = PowerMockito.mock(C.class);
PowerMockito.doCallRealMethod().when(classUnderTest, "testMeAnother");
PowerMockito.doCallRealMethod().when(classUnderTest, "testMe");
PowerMockito.doCallRealMethod().when(classUnderTest, "myMethod");
PowerMockito.doCallRealMethod().when(classUnderTest, "another");
classUnderTest.testMeAnother();
classUnderTest.testMe();
//this works as expected
PowerMockito.verifyPrivate(classUnderTest, times(1))
.invoke(PowerMockito.method(C.class, "another"))
.withNoArguments();
//this raises an TooManymethodsFoundException:
// Matching:
// void myMethod(...)
// void myMethod(...)
// void myMethod(...)
// three times!
PowerMockito
.verifyPrivate(classUnderTest, times(1))
.invoke(PowerMockito.method(C.class, "myMethod",
Exception[].class))
.withArguments(any(Exception[].class));
}
}
//是的,我直接在mock上调用方法,无论这个代码片段
可以找到给定测试的完整堆栈strace there
提前致谢!