Home > Back-end >  How do I read properties from ".properties" files in unit tests?
How do I read properties from ".properties" files in unit tests?

Time:01-29

In product code, I can use the following code to read the aws.default.region property from application.properties and application-development.properties

@Value("${aws.default.region:null}")
private String awsDefaultRegion;

However, in unit test the same code doesn't work, and awsDefaultRegion variable is always null.

I tried to add the following annotation but it doesn't work.

@PropertySource({
        "classpath:application.properties",
        "classpath:application-development.properties"
})

CodePudding user response:

If you use JUnit:

@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource("classpath:test-application.properties")

CodePudding user response:

I think inject value on test could be another good way


ReflectionTestUtils.setField(
   serviceMocked, 
  "awsDefaultRegion",  // name attr in service
   valueaTobeInjectWhenTesting
);

// rest of test method

  •  Tags:  
  • Related