简体   繁体   English

如何在单元测试中从“.properties”文件中读取属性?

[英]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在产品代码中,我可以使用以下代码从application.propertiesapplication-development.properties读取aws.default.region属性

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

However, in unit test the same code doesn't work, and awsDefaultRegion variable is always null.但是,在单元测试中,相同的代码不起作用,并且awsDefaultRegion变量始终为 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:如果您使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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