简体   繁体   中英

how to use Mockito or PowerMock to set a private field in a class

I have a following code

@RunWith(PowerMockRunner.class)
public NeedToTestClass () {
     private String needToSetValueField;

     ......

     public String needToTestMethod() {
           return "the field value is " + this.needToSetValueField;
     } 
}

Is there anyway I can set(or mock) the needToSetValueField when I try to test the method? Please help. Thanks.

@Taschi should get the credit. A simple reflection can be used to set a private variable in the class. What can be done in unit test is to mock the class NeedToTestClass using spy annotation and then use reflection to set the private variable needToSetValueField. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM