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

时间:2015-06-09 11:04:14

标签: java powermock white-box white-box-testing

当我尝试使用PowerMock 1.5.2(我们在我公司使用)运行PowerMock' Bypass Encapsulation docs中的第二个示例时,我立即得到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;,   java.lang.Integer] at   org.powermock.reflect.internal.WhiteboxImpl.invokeConstructor(WhiteboxImpl.java:1354)     在   org.powermock.reflect.Whitebox.invokeConstructor(Whitebox.java:511)     在Test.test(Test.java:6)......

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

1 个答案:

答案 0 :(得分:1)

这个例子中一定是个错误。查看public static <T> T invokeConstructor(Class<T> classThatContainsTheConstructorToTest, Class<?>[] parameterTypes, Object[] arguments)的签名,您应该传递一个Object数组作为最后一个参数。我稍微修改了一些例子来说明这一点。

测试

@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