How to override the field value entered by @Value in Spring?

I have a class with a field entered from a property with @Value:

public class MyClass {
    @Value(${property.key})
    private String filePath;
    ...

My integration tests should change filePathto point to several different files.

I tried using reflection to set it before calling the 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 is called, the injection @Valuestarts and changes the value from the just set. Can anyone suggest how to solve this or an alternative approach?

Note: I need Spring to manage the class (so other dependencies are introduced), and other tests are needed for the same class using different test files.

+4
2

. , , . , , Spring mocks.

+3

spring

dev, prod,

@Configuration
public class AppConfiguration {

    @Value("${prop.name}")
    private String prop;


    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }


    @Configuration
    @Profile("dev")
    @PropertySource("classpath:dev.properties")
    public static class DevAppConfig {
    }

    @Configuration
    @Profile("test")
    @PropertySource("classpath:test.properties")
    public static class TestAppConfig {
    }
}

@ActiveProfile("test")

+1

Source: https://habr.com/ru/post/1613325/


All Articles