鉴于以下代码:的Mockito - 惩戒具体类
LinkedList list = mock(LinkedList.class);
doCallRealMethod().when(list).clear();
list.clear();
通过执行该试验中,一个NullPointerException是从链表#第一线清晰抛出:
public void clear() {
Entry<E> e = header.next;
while (e != header) {
Entry<E> next = e.next;
//Code omitted.
但头一直实例化之前:
private transient Entry<E> header = new Entry<E>(null, null, null);
莫非一些请解释模拟创作过程中发生了什么?
#######更新。 ######
阅读所有答案,特别是Ajay的答案后,我查看了Objenesis源代码,并发现它使用Reflection API创建代理实例(通过CGLIB),因此绕过层次结构中的所有构造函数直到java.lang.Object。
下面是示例代码模拟了问题:
public class ReflectionConstructorTest {
@Test
public void testAgain() {
try {
//java.lang.Object default constructor
Constructor javaLangObjectConstructor = Object.class
.getConstructor((Class[]) null);
Constructor mungedConstructor = ReflectionFactory
.getReflectionFactory()
.newConstructorForSerialization(CustomClient.class, javaLangObjectConstructor);
mungedConstructor.setAccessible(true);
//Creates new client instance without calling its constructor
//Thus "name" is not initialized.
Object client = mungedConstructor.newInstance((Object[]) null);
//this will print "CustomClient"
System.out.println(client.getClass());
//this will print "CustomClient: null". name is null.
System.out.println(client.toString());
} catch(Exception e) {
e.printStackTrace();
}
}
}
class CustomClient {
private String name;
CustomClient() {
System.out.println(this.getClass().getSimpleName() + " - Constructor");
this.name = "My Name";
}
@Override
public String toString() {
return this.getClass().getSimpleName() + ": " + name;
}
}
我们展示了全堆栈跟踪 – Archer