为什么 PowerMock 使用 Whitebox.invokeConstructor() 的示例抛出 ConstructorNotFoundException?

Why does PowerMock's example for use of Whitebox.invokeConstructor() throw a ConstructorNotFoundException?

然后当我尝试 运行 PowerMock Bypass Encapsulation docs 的第二个示例时,使用 PowerMock 1.5.2(我们在我的公司使用),我立即得到一个 ConstructorNotFoundException 抛出.我尝试切换到1.6.2版本,结果相同。

知道我可能做错了什么吗? (根据示例,我没有使用任何 PowerMock 注释,并且是 运行ning 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>

这是测试 class:

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: Failed to find a constructor with parameter types: [[Ljava.lang.Class;, java.lang.Integer] at org.powermock.reflect.internal.WhiteboxImpl.invokeConstructor(WhiteboxImpl.java:1354) at org.powermock.reflect.Whitebox.invokeConstructor(Whitebox.java:511) at Test.test(Test.java:6) ...

有什么想法吗?我确定我缺少的东西非常简单...

这一定是例子中的一个错误。查看 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();
}

class:

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