I have a class with a field injected from a property using @Value
:
public class MyClass {
@Value(${property.key})
private String filePath;
...
My integration tests need to change filePath
to point at some different files.
I tried using reflection to set it before invoking a method:
public class MyClassIT {
@Autowired MyClass myClass;
@Test
public void testMyClassWithTestFile1 {
ReflectionTestUtils.setField(myClass, "filePath", "/tests/testfile1.csv");
myClass.invokeMethod1();
...
But when the first method gets invoked, the @Value
injection kicks in and changes the value from what was just set. Could anyone suggest how to resolve this or an alternative approach?
Note: I need Spring to be managing the class (so other dependencies are injected) and other tests are needed for the same class using different test files.
Just use a setter. It's usually preferable to use setter injection instead of field injection anyhow. Even better, convert entirely to constructor and setter injection, and you can usually replace your Spring test context with mocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With