我们可以为 JUnit 测试模拟 class 的私有字段吗?

Can we mock private fields of a class for JUnit testing?

如果要测试的 class 的某些 public 方法正在使用私有字段,那么我们可以在 JUnit 测试方法中模拟该私有字段吗? 否则,如果您无权访问私有字段,则无法使用或修改其值并将其传递给 JUnit 测试以查看不同的结果。

使用反射(以下示例不是 JUnit 测试,但它的工作原理完全相同)。

示例 class 使用 private 变量和 print() 方法以确保 set 成功。

public class Whosebug2 {
    private int testPrivate = 10;
    public void print(){
        System.out.println(testPrivate);
    }
}

使用反射以及 getset 方法调用 class。注意,设置 testPrivateReflection 不会改变 testPrivate 因为它是该值的本地副本,因此我们使用 set.

public class Whosebug {
    public static void main(String[] args) throws IllegalArgumentException, 
            IllegalAccessException, NoSuchFieldException {
        Whosebug2 sf2 = new Whosebug2();
        Field f = sf2.getClass().getDeclaredField("testPrivate");
        f.setAccessible(true);
        int testPrivateReflection = (int)f.get(sf2);
        System.out.println(testPrivateReflection);
        f.set(sf2, 15);
        sf2.print();
    }
}