简体   繁体   中英

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?

If you're running @SpringBootTest you can use this annotations:

@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

 @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

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

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