You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ReflectionTestUtils.setField() should not call toString() on the target [SPR-9571] #14205
ReflectionTestUtils.setField() is implicitly calling toString() on the target when arguments for a call to Assert.notNull() are built, which can have side effects, specifically (line 107):
Field field = ReflectionUtils.findField(target.getClass(), name, type);
Assert.notNull(field, "Could not find field [" + name + "] on target [" + target + "]");
For example, a lot of our database models have a toString() which dumps properties, which can try and hit the database. If the connection is null a new one is created. I am unable to inject a mock connection into the model with setField() from 3.1+ because during injection a call to toString() happens which will trigger initialization and try and use a real connection instead of using my mock.
In 3.0.6, the toString() was wrapped in a null check so it only happened on error instead of when the arguments to Assert.notNull() are built.
You could argue that toString() shouldn't have side effects, but ReflectionTestUtils is often used on questionable, legacy code to make it testable.
I've reverted to spring-test 3.0.6 in the meantime.
RTU.setField() shouldn't call toString() on target
ReflectionTestUtils.setField() implicitly calls toString() on the target
object when arguments for a call to Assert.notNull() are built. This can
have undesirable side effects, for example if the toString() invocation
results in a thrown exception or access to an external system (e.g., a
database).
This commit addresses this issue by inlining the Assert.notNull() code,
thereby avoiding accidental invocation of toString() on a non-null
target.
Activity
spring-projects-issues commentedon Aug 10, 2012
Sam Brannen commented
Hi John,
Yes, I would definitely argue that invoking
toString()should never have side effects, especially not related to external systems (e.g., databases).However, I also understand your argument regarding questionable legacy code that is out of your control. So I think we can do something about this.
- Sam
spring-projects-issues commentedon Aug 10, 2012
Sam Brannen commented
Completed as described in the message for GitHub commit df961a938e1f0811ac1cbd679f35de9e4d0eb8c6.