将spock特征方法内的资源放置在任意位置

问题描述 投票:1回答:1

在spock测试中,我们想创建一个资源,并确保正确地处置该资源,而不考虑测试结果如何。

我们尝试了以下方法。但是,当测试代码包装在闭包中时,spock不会执行测试。

import spock.lang.Specification

class ExampleSpec extends Specification {

    def wrapperFunction(Closure cl) {
        try {
            cl()
        } finally {
            // do custom stuff
        }
    }

    def "test wrapped in closure"() {
        wrapperFunction {
            expect:
            1 == 1
            println "will not execute!"
        }
    }
}

在spock测试中创建和配置资源的最佳方法是什么?

[setup()cleanup()是不可行的解决方案,因为在特征方法内部的任意点都应该可以创建和处置。

groovy spock
1个回答
0
投票

您可以像这样在测试用例(功能方法)内使用setupcleanup块:

class ReleaseResourcesSpec extends Specification {
    void 'Resources are released'() {
        setup:
        def stream = new FileInputStream('/etc/hosts')

        when:
        throw new IllegalStateException('test')

        then:
        true

        cleanup:
        stream.close()
        println 'stream was closed'
    }
}

C0]块中的代码始终会执行,尽管测试失败或有任何异常。请参阅以上示例的结果:cleanup

因此它类似于enter image description heresetup()方法,但是在这种情况下,您可以为每个功能方法使用不同的设置和清除代码。

© www.soinside.com 2019 - 2024. All rights reserved.