我有一个A类,看起来像这样:
public class A {
// there is a public API that uses both
// method1 and method2, but that's not important
// in this question.
public Integer publicApi(Integer a, Integer b) {
// a bunch of other stuff is done that is
// not related to method1 or method2 here.
// However, method1 IS used somewhere in here.
// For now, I don't want to test other
// implementation details for this API, I only
// am interested in testing method1.
return method1(a, b);
}
private static Integer method1(Integer a, Integer b) {
if(method2(a, b, 10) == null) {
return -1;
}
return 10 + method2(a, b, 10);
}
private static Integer method2(Integer a, Integer b, Integer c) {
// some complicated logic with multiple values
// to return (based on various conditions).
// however, I want to simply test what happens
// when this method returns null (which is a possibility).
return a+b+c;
}
}
如所给出的,我的A类有一个公共API,其中有(某种程度上)复杂的逻辑,而我并不想为此测试它(就这个问题而言)。假设我只对测试method1
感兴趣。
以下是我的测试代码(我使用PowerMockito):
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.lang.reflect.Method;
import static org.junit.Assert.assertNull;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class SimpleTest {
@Test
public void testMethod1Invocation() throws Exception {
spy(A.class);
when(A.class, method(A.class,
"method2", Integer.class,
Integer.class, Integer.class))
.withArguments(1, 2, 10)
.thenReturn(null);
// use reflection to call method1
Method method1 = A.class.getDeclaredMethod(
"method1",
Integer.class, Integer.class
);
method1.setAccessible(true);
Object ret = method1.invoke(1, 2);
assertEquals(-1, ret);
}
}
但是,我遇到了以下错误:
com.apple.geo.tart.A.method1(java.lang.Integer, java.lang.Integer, java.lang.Integer)
java.lang.NoSuchMethodException: com.apple.geo.tart.A.method1(java.lang.Integer, java.lang.Integer, java.lang.Integer)
at java.lang.Class.getDeclaredMethod(Class.java:2130)
at com.apple.geo.tart.SimpleTest.testMethod1Invocation(SimpleTest.java:32)
我不明白我做错了什么,据我所知,这里需要3件事:
- 监听
A
,以便可以模拟静态方法的 when/thenReturn。 - 模拟我想要的私有静态方法(在本例中是
method2
)。 - 使用反射访问
method1
,然后调用它。
method1
方法,但是你的代码只传入了 2 个参数。尝试重新编译你的项目 -- 看起来代码没有引用测试中的二进制文件。 - Sergey Grinevmethod1.invoke(...)
上。它所需的第一个参数是要调用方法的对象,而不是实际的参数!当测试类的静态方法时,通常为null
。将该方法调用更改为method1.invoke(null, 1, 2)
即可得到预期结果。 - Nishant Kelkar