Mock private static final variables in the testing class

我的未来我决定 提交于 2019-12-19 04:48:06

问题


I have a few private static final fields in the class I want to test. Like follows

public class ClassToTest{
    ....
    private static final Myclass myclass = MyClassFactory.getMyClass(type.firstType);
    ....
}

The type is a enum in the MyClassFactory. That factory do is it initialize object according to type passed and return.

My question is does powermock support this and if so how to do this.


回答1:


You can use reflection also if any mock library works for you.

Field f = classToTest.getclass().getDeclaredField("myclass ");
f.setAccessible(true);
f.set(classToTest,/*NEW VALUE*/);



回答2:


PowerMock ( + a mocking framework ) will allow you to do this. Presumeably you're talking about mocking MyClassFactory.getMyClass() ?

See this question for an example




回答3:


Why do you want to test this value? Shouldn't you test your enum, test if it returns the correct value when a given type is passed to it. If you want to test the assignment of the enum to the field you are doubting basic java assignment.



来源:https://stackoverflow.com/questions/19426999/mock-private-static-final-variables-in-the-testing-class

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