简体   繁体   中英

How do I read properties from ".properties" files in unit tests?

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"
})

If you use JUnit:

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

I think inject value on test could be another good way


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

// rest of test method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM