No Private Setter for Fields - Unit Testing Legacy Code

别说谁变了你拦得住时间么 提交于 2019-12-12 02:57:13

问题


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


回答1:


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);



回答2:


Technically this would only be possible by using reflection, but in such case it is an incredibly bad idea.



来源:https://stackoverflow.com/questions/24807138/no-private-setter-for-fields-unit-testing-legacy-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!