Skip to content

ReflectionTestUtils.setField() should not call toString() on the target [SPR-9571] #14205

Closed
@spring-projects-issues

Description

@spring-projects-issues

John Richardson opened SPR-9571 and commented

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.


Affects: 3.1.1

Issue Links:

Metadata

Metadata

Assignees

Labels

in: testIssues in the test moduletype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions