gpt4 book ai didi

java - 如何将 JUnit TemporaryFolder @Rule 与 Spring @Value 属性一起使用?

转载 作者:行者123 更新时间:2023-11-30 05:25:33 25 4
gpt4 key购买 nike

我可以在 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 中的属性 @ClassRuleApplicationContextInitializer 来解决这个问题。虽然它有效,但可能还有我仍然感兴趣的更好的解决方案!

@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com