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

标签 java spring spring-boot junit spring-boot-test

我可以在 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/

相关文章:

java - hsqldb 脚本文件出现唯一约束违规异常(未读取空格字符)

java - BindingResult 和 bean 名称 'owner' 的普通目标对象都不能作为请求属性

java - Spring Security登录中的无限循环

java - Spring boot Bean异常: Cannot determine embedded database driver class for database type NONE

java - spring boot 集成测试中获取 org.hibernate.LazyInitializationException

java - 是否可以阻止 Gradle 添加排除的传递依赖项?

c# - 泛型、ToArray 等

java - 当配置设置为另一个时,Idea + Spring Boot + Tomcat 在端口 8080 上启动

spring - Tomcat 中的 LTPA token (Spring security)

spring - ThreadPoolTask​​Executor中的TaskRejectedException