EasyMock-由于父类私有对象(i18n)无法访问而抛出NullPointerException [英] EasyMock - Throwing NullPointerexception due to not accessible to parent class private object(i18n)

查看:213
本文介绍了EasyMock-由于父类私有对象(i18n)无法访问而抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A)
Class Parent4{
    private I18nUtils i18n;

    //-----------Here Nullpointerexception occur----------------
    public Parent4(){
         SetText(i18n.getText("HELLO");
    }
}

B)
Class Parent3 extends Parent4{
    private I18nUtils i18n;
}

C)
Class ParentParent2 extends Parent3{
    private I18nUtils i18n;
}

D)
Class Parent extends ParentParent2{
    private I18nUtils i18n;
}

E)
Class Child extends Parent{
    protected method_name(){
    //.......DO Something......
    }
}



My Test Class:

public testclass{
        Class cls = Class.forName("Child");
        Object obj = cls.newInstance();
        Method method = cls.getDeclaredMethod("method_name",Null);
        method.setAccessible(true);
        method.invoke(obj, null);

因此,在创建子类的对象时,它将调用并调用子类的所有依赖关系并使用模拟对象进行初始化并调用了所有父类及其构造函数。

So while creating object of child class it called and invoke all dependency of child class and initialize with mock object and called all parent class and its constructor.

而i18n默认设置为null。
1)我试图通过反射进行访问。借助superClass()。getDeclared( i18n)。但是最终它只能访问其先前的类。因此,它没有设置Parent5()类的值。

While i18n is set null by default. 1) I tried to accessed with reflection. with the help superClass().getDeclared("i18n"). But eventually it only access to its preceding class only. So it not set the value for Parent5() class.

2)另外,我还尝试直接访问Parent5类的i18n字段。
但是在调用子类时。它将创建新实例,并且与将parent5()类i18n重置为null相同。

2) Also I have tried to direct access Parent5 class i18n field. But when invoking the child class. It will create new instance and same as that it will reset parent5() class i18n as null.

推荐答案

我可能会处理这种情况。我阅读了Easymock文档。从那里,我得到了类似的情况来处理这种情况。

I probably handle this situation. I read the Easymock documentation. From there I got some similar case to handle this kind of situtation.

此处的代码:

Objenesis objenesis = new ObjenesisStd(); // or ObjenesisSerializer
child obj_1 = objenesis.newInstance(child.class);
Method method = obj_1.getClass().getDeclaredMethod("method_name",MessageReceiver.class);
method.setAccessible(true);
method.invoke(obj_1, null);

就我而言,它可以正常工作。因此,我无法在任何地方模拟父字段。

For my case it working fine. As such I did not able to mock parent field anywhere.

注意:我在子类上没有任何父类的字段依赖项方法。只有我需要模拟(i18n)字段,这样它才不会导致 nullpointerexception。但是最终我还是使用objensis。

NOTE: I did not have any field dependency of parent class on my child class method. Only I need to mock the (i18n) field so it does not cause "nullpointerexception". But eventually I handle with objensis.

这篇关于EasyMock-由于父类私有对象(i18n)无法访问而抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆