【发布时间】:2016-06-28 08:14:22
【问题描述】:
我有一个 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)
我看不出我在这里做错了什么。在我看来,这里需要三件事:
- 监视
A,这样我就可以模拟when/thenReturn on the static 方法。 - 模拟我感兴趣的私有静态方法(在本例中为
method2)。 - 使用反射访问
method1,然后调用它。
然后我如何模拟私有静态方法(method2),以便我可以测试依赖于第一个的同一类的另一个私有静态方法(method1)?
【问题讨论】:
-
是否绝对有必要测试私有方法?一般来说,您应该只为公共方法编写测试。您可以输入
verify以查看是否在私有方法中调用了您的任何模拟。 -
异常表示您使用 3 个参数查找
method1,而您的代码显示 2 个参数调用。尝试重新编译你的项目——看起来代码没有引用被测试的二进制文件。 -
@SergeyGrinev 我确实尝试过,清除了构建目录,并重新组装了代码(使用 Gradle)。但我仍然得到同样的错误。
-
@all,发现问题了。问题是
method1.invoke(...)。它采用的第一个参数是调用方法的 object,而不是实际的 args!测试类的静态方法时,通常是null。将该方法调用更改为method1.invoke(null, 1, 2)会产生预期的结果。
标签: java junit powermockito