当我尝试使用PowerMock 1.5.2(我们在我的公司使用)运行PowerMock的旁路封装文档中的第二个示例时,我立即得到一个ConstructorNotFoundException
抛出。我试着切换到1.6.2版本,结果是一样的。
知道我可能做错了什么吗?(例如,我没有使用任何PowerMock注释,并且正在运行Java 1.7。)我敢肯定这一定是我的疏忽……
下面是我对文档中示例的POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>PowerMock</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-mockito-release-full</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
</project>
下面是测试类:
import org.powermock.reflect.Whitebox;
public class Test {
@org.junit.Test
public void test() throws Exception {
PrivateConstructorInstantiationDemo instance = Whitebox.invokeConstructor(PrivateConstructorInstantiationDemo.class, new Class<?>[]{Integer.class}, 43);
System.out.println();
}
}
这里有一个例外:
org.powermock.reflect.exceptions。ConstructorNotFoundException:失败[[Ljava.lang.Class;,. lang。整数)org.powermock.reflect.internal.WhiteboxImpl.invokeConstructor (WhiteboxImpl.java: 1354)在org.powermock.reflect.Whitebox.invokeConstructor (Whitebox.java: 511)
任何想法?
这一定是示例中的错误。看看public static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Class<?>[] parameterTypes, Object[] arguments)
的签名,您应该传递一个对象数组作为最后一个参数。为了说明这一点,我稍微修改了一下示例。
:
@org.junit.Test
public void test() throws Exception {
PrivateConstructorInstantiationDemo instance1 = Whitebox.invokeConstructor(PrivateConstructorInstantiationDemo.class, new Class<?>[]{Integer.TYPE}, new Object[]{43});
PrivateConstructorInstantiationDemo instance2 = Whitebox.invokeConstructor(PrivateConstructorInstantiationDemo.class, new Class<?>[]{Integer.class}, new Object[]{43});
System.out.println();
}
类:
public static class PrivateConstructorInstantiationDemo {
private final int state;
private PrivateConstructorInstantiationDemo(int state) {
this.state = state;
System.out.println("int " + state);
}
private PrivateConstructorInstantiationDemo(Integer state) {
this.state = state;
System.out.println("Integer " + state);
// do something else
}
public int getState() {
return state;
}
}
测试输出:int 43
Integer 43