How to mock final field? mockito/powermock

后端 未结 2 625
栀梦
栀梦 2021-01-12 07:10

I have same class

class MyCalss{
     final static SomeClass field  = new SomeClass();
     ...
}

I should to mock instance of MyCalss. Thi

2条回答
  •  天涯浪人
    2021-01-12 08:01

    Mocking operates on methods and interfaces, not fields; furthermore, it operates on instance members, not static members. Mockito and Powermock are not the right tools to solve this problem.

    Though you can use reflection to set final fields, you're effectively working around your own declaration, and are subject to the limitations and hazards of JLS 17.5.3.

    A better design would be to rewrite the method in the system under test to inject its SomeClass dependency:

    public void methodUnderTest() {
      methodUnderTest(MyClass.field);
    }
    
    /** Package-visible for testing. Test this method instead. */
    void methodUnderTest(SomeClass someClass) {
      someClass.firePhotonTorpedoes();
    }
    

提交回复
热议问题