How can you assign a mock to a private static field in Java 17?

68 Views Asked by At

Suppose I need to assert on the behavior of an object stored in a private static final field (and I can't change the modifiers because, for example, it's a write-only class or generated code)

public class SomeClass {
    private static final HardCodedDependency hardCodedDependency = HardCodedDependency.getInstance();
    
    public void doSomething() {
        // I need to make sure someMethod() is invoked on HardCodedDependency on every doSomething() invocation
        hardCodedDependency.someMethod();
    }
}

I need to instantiate SomeClass and then reassign a mock to constantField

I discovered there are some limitations starting from at least JDK17 (my JDK's version). I can no longer pull this off:

    @SneakyThrows
    private void makeNonFinal(Field field) {
        Field modifiersField = Field.class.getDeclaredField("modifiers"); // throws
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    }

Apparently, you'd need to run your code with CLI arguments (which I don't want to do)

java --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED Main

or you PowerMock

Unfortunately, I didn't find code samples showing that

Can you give me an example of how I can achieve my goal with PowerMock?

0

There are 0 best solutions below