简体   繁体   English

在测试中使用classpath覆盖spring资源值

[英]Override spring resource value with classpath in test

I wanna override the value of a resource in a test: 我想在测试中覆盖资源的值:

@SpringBootConfiguration
public class MyExampleConfig {

  @Value("classpath:my-example-resource.yml")
  private Resource myExampleResource;

}

Does anybody know how I could override the value "classpath:my-example-resource.yml"in my test? 有人知道我可以在测试中覆盖值“ classpath:my-example-resource.yml”吗?

If you're running @SpringBootTest you can use this annotations: 如果您正在运行@SpringBootTest,则可以使用以下注释:

@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
        "key=value",
        "key=value"
})

They will override default ones. 它们将覆盖默认值。

You can have a separate application.properties file for your test package under resources, and you can define a key value pair ie : classpath=classpath:my-example-resource.yml in this file and use in the code as follows 您可以在资源下为测试包提供一个单独的application.properties文件,并且可以在该文件中定义一个键值对,即: classpath=classpath:my-example-resource.yml并在代码中使用,如下所示

 @Value("${classpath}")
 private String classpath;

You can use create test configuration ( ApplicationTest ) with test .properties or .yml in test package and then use it in your tests 您可以在测试包中使用带有测试.properties.yml创建测试配置( ApplicationTest ),然后在测试中使用它

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ApplicationTest.class)
public class Test {
    @Test
    public void test() throws Exception {
      //some code
    }
}

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

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