Search code examples
javaunit-testingfieldprivatelegacy

No Private Setter for Fields - Unit Testing Legacy Code


For testing MyClass -

I Have:

 MyClass{
         private MyThing usedThing = new MyThing(); 

         public String funcToTest(){
               return usedThing.Fields.something.ToString(); 
         }
 }

QUESTION: This is only a section of the method, but my question is without a setter, or without changing the prod code, how can I inject the mocked MyThing object into the test?

thanks


Solution

  • You can use reflection for that. It is bad, because it allows you to use private methods or fields outside the owning class, breaking the encapsulation. But testing is a use case where it makes sense.

    You can access you private field from your test class the following way :

    MyClass myClass = new MyClass();
    Field field = MyClass.class.getDeclaredField("usedThing");
    field.setAccessible(true); // to allow the access for a private field
    field.set(myClass, myMock);