我正在使用 junit 的 TemporaryFolder 来测试我的应用程序中处理文件系统的部分。是否可以将 junit 变量 java.io.tmpdir 设置为运行配置中的环境变量?
最佳答案
根据我们长期的讨论,我现在明白您问的是:
How to configure JUnit so it uses a specific folder for creating the temporary files.
(如果我正确地理解了您的问题,请进行相应的编辑并更改标题。)
JUnit 4.11+
最简单的方法是使用新的构造函数 TemporaryFolder(File parentFolder) 。这是首选方式。
JUnit<4.11
您知道org.junit.rules.TemporaryFolder使用系统属性java.io.tmpdir
。实际上,当你查看源代码时,它在内部使用 File.createTempFile(prefix, suffix)使用此系统属性的方法。
您可以在这里找到详尽的信息:Environment variable to control java.io.tmpdir? 。
有关系统属性和环境变量的更一般信息:Java system properties and environment variables
但是,你应该注意到Java-doc中的这句话。 :
A different value may be given to this system property when the Java virtual machine is invoked, but programmatic changes to this property are not guaranteed to have any effect upon the temporary directory used by this method.
如果您想确保临时文件夹始终处于您的控制之下,您可以create your own org.junit.rules.TemporaryFolder 的版本 - 这并不难,你只需使用 File.createTempFile(prefix, suffix, directory)显式分配第三个参数目录
。
关于java - 如何将 junit TemporaryFolder 的位置设置为环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23659408/