EasyMock - Throwing NullPointerexception due to not accessible to parent class private object(i18n)

依然范特西╮ 提交于 2020-02-04 03:53:57

问题


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.

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) 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.


回答1:


I will answer following one of your comments.

Yes, calling another method instead of super and using a partial mock is a correct solution. EasyMock can't mock super.

Then, if you want to mock a method called by a constructor, that's indeed impossible. EasyMock doesn't provide a way to mock before having the mock.

In both cases, modifying the design will probably improve the design.




回答2:


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

Code here:

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.

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.



来源:https://stackoverflow.com/questions/58509820/easymock-throwing-nullpointerexception-due-to-not-accessible-to-parent-class-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!