Search code examples
javaunit-testingdependency-injectionmockingpowermock

How to mock String value of injected properties file value?


I got this member in my service class:

@Value("${dynamodb.aws.region}")
private String region;

When using the class on production, the value in being injected using Spring from my .properties file.

Then, in test mode, I need to check this code:

@Override
public void init() {
    if (StringUtils.isEmpty(region)){
        String msg = "Connection to DynamoDB couldn't be established. Region value is empty.";
        logger.error(msg);
        throw new IllegalArgumentException(msg);
    }
    this.dynamoDB = new DynamoDB(Regions.fromName(region));
}

Except using getters and setters, What is the best way to inject this value on test ?


Solution

  • use the Spring ReflectionTestUtils to set the property value from Test class.

    ReflectionTestUtils.setField(targetObject, name, value);
    

    Link to Javadoc