Java 在测试类中模拟私有静态最终变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19426999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:03:45  来源:igfitidea点击:

Mock private static final variables in the testing class

javajunitjunit4easymockpowermock

提问by Susitha Ravinda Senarath

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.

该类型是 MyClassFactory 中的一个枚举。该工厂所做的是根据传递和返回的类型初始化对象。

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

我的问题是 powermock 是否支持这一点,如果支持,如何做到这一点。

回答by DaveH

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

PowerMock(+ 一个模拟框架)将允许您执行此操作。大概你在谈论嘲笑 MyClassFactory.getMyClass() ?

See this questionfor an example

请参阅此问题以获取示例

回答by RamonBoza

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*/);

回答by Tom Jonckheere

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.

为什么要测试这个值?你不应该测试你的枚举,测试当给定类型传递给它时它是否返回正确的值。如果您想测试枚举对字段的分配,您会怀疑基本的 java 分配。