gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:27:05 29 4
gpt4 key购买 nike

当我尝试运行 PowerMock 的 Bypass Encapsulation docs 中的第二个示例时,使用 PowerMock 1.5.2(我们在我的公司使用),我立即抛出一个 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();
}
}

以下是其所有荣耀中的异常(exception):

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

关于java - 为什么 PowerMock 使用 Whitebox.invokeConstructor() 的示例会抛出 ConstructorNotFoundException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30730236/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com