Unit testing 斯波克:可以指定在哪里创建tempDir吗?

Unit testing 斯波克:可以指定在哪里创建tempDir吗?,unit-testing,groovy,spock,Unit Testing,Groovy,Spock,spock中有一个有用的注释@TempDir,可以帮助我们创建临时文件夹并自动删除它。注释类的全名如下所示: com.github.goldin.spock.extensions.tempdir.tempdir 它通常在定义为TMP环境变量的文件夹中创建临时文件夹。一个问题是:是否可以以某种方式指定创建临时文件夹的文件夹?您可以使用@RestoreSystemProperties和System.setProperty()的组合: 如果您想在测试期间对该函数进行更多控制,可以创建自己的JUnit@

spock中有一个有用的注释@TempDir,可以帮助我们创建临时文件夹并自动删除它。注释类的全名如下所示:

com.github.goldin.spock.extensions.tempdir.tempdir


它通常在定义为TMP环境变量的文件夹中创建临时文件夹。一个问题是:是否可以以某种方式指定创建临时文件夹的文件夹?

您可以使用
@RestoreSystemProperties
System.setProperty()的组合:


如果您想在测试期间对该函数进行更多控制,可以创建自己的JUnit@Rule

是否无法使用System.setProperty(“java.io.tmpdir”,“tmp”)覆盖
java.io.tmpdir
;在
设置
方法中,并在
清理
方法中将其设置回原始值?这是可能的。但这看起来像是一个更改,可能会影响同一实例上同时运行的其他任务。例如,如果我们在TeamCity上运行此测试,这可能会导致其他构建执行出现许多问题。
@RestoreSystemProperties
class TmpSpec extends Specification {

    def setup() {
        System.properties['java.io.tmpdir'] = "target/test"
        new File("target/test").mkdirs()
    }

    def "create a tmp file"() {
        given: "a tmp file"
            def file = File.createTempDir()

        expect:
            file.path.contains("target/test")

    }

}