0

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.

Laodao
  • 1,547
  • 3
  • 17
  • 39
  • You shouldn't. Private members aren't part of the class's contract. If you can explain what the purpose of this private field is, we may be able to suggest some cleaner alternatives. – chrylis -cautiouslyoptimistic- May 30 '20 at 18:33
  • @chrylis, thanks for ur replying. this private field value supposed to be calculated once when the class is instantiated and being used in different places. – Laodao May 30 '20 at 19:29
  • Use the Reflection API. Example: https://stackoverflow.com/questions/32716952/set-private-field-value-with-reflection –  May 30 '20 at 20:25
  • No, I can't - StackOverflow considers it trivial and automatically converts it to a comment. Sorry. –  May 31 '20 at 15:15

1 Answers1

0

@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.

Laodao
  • 1,547
  • 3
  • 17
  • 39