我可以在 junit
测试中生成 TemporaryFolder
,并使用该文件夹作为 @Value
属性的前缀吗?
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
@Autowired
private MyService service;
@Test
public void test() {
//TODO how to rewrite the application property with the tmp folder created?
service.run();
}
}
@Service
public class MyService {
@Value("${my.export.path}")
private String path;
public void run() {
//generates a file and exports it to @Value path
}
}
应用程序属性:
my.export.path=/var/www/export.csv
我当然想将导出路径设置为生成的tmp文件夹。但如何呢?
最佳答案
我可以通过重写 ApplicationContext
中的属性 @ClassRule
和 ApplicationContextInitializer
来解决这个问题。虽然它有效,但可能还有我仍然感兴趣的更好的解决方案!
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(initializers = TemporaryFolderInitializer.class)
public class MyTest {
@ClassRule
public static TemporaryFolder tmp = new TemporaryFolder();
public static class TemporaryFolderInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(applicationContext, "my.export.path=" + tmp.getRoot().getAbsolutePath());
}
}
}
关于java - 如何将 JUnit TemporaryFolder @Rule 与 Spring @Value 属性一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713410/