问题
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