Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock private static final field

Tags:

java

mocking

I have class which I need test:

class MyClass {
    private final static MyOtherClass myOtherClass = OtherClassFactory.get();
    public void doSomething() {}
}

How to mock myOtherClass in unit test?

like image 272
krynio Avatar asked Dec 07 '25 03:12

krynio


1 Answers

You can use the Deencapsulation.setField method from the JMockit mocking library; it supports setting of final fields as well (as long as the field is not initialized to a compile-time constant, which is not the case here).

like image 125
Rogério Avatar answered Dec 09 '25 17:12

Rogério



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!