Testing 在没有安装的情况下运行特定的Spock测试?

Testing 在没有安装的情况下运行特定的Spock测试?,testing,spock,Testing,Spock,在Spock中,在“夹具方法”一节中提到了这些功能: def setup() {} // run before every feature method def cleanup() {} // run after every feature method def setupSpec() {} // run before the first feature method def cleanupSpec() {} // run after the last

在Spock中,在“夹具方法”一节中提到了这些功能:

def setup() {}          // run before every feature method
def cleanup() {}        // run after every feature method
def setupSpec() {}     // run before the first feature method
def cleanupSpec() {}   // run after the last feature method
我正在使用setup函数初始化所有测试的新对象。然而,有些测试应该测试当没有其他对象时会发生什么

由于设置原因,这些测试现在失败

有没有办法暂停某些功能的设置?也许是注释


或者我必须创建一个单独的“setup”函数,并在每次测试中调用它们。大多数测试都使用它

您始终可以仅为特定方法覆盖测试方法内的值。请看以下示例:

import spock.lang.Shared
import spock.lang.Specification

class SpockDemoSpec extends Specification {

    String a
    String b

    @Shared
    String c

    def setup() {
        println "This method is executed before each specification"
        a = "A value"
        b = "B value"
    }

    def setupSpec() {
        println "This method is executed only one time before all other specifications"
        c = "C value"
    }

    def "A empty"() {
        setup:
        a = ""

        when:
        def result = doSomething(a)

        then:
        result == ""
    }

    def "A"() {
        when:
        def result = doSomething(a)

        then:
        result == "A VALUE"

    }

    def "A NullPointerException"() {
        setup:
        a = null

        when:
        def result = doSomething(a)

        then:
        thrown NullPointerException
    }

    def "C"() {
        when:
        def result = doSomething(c)

        then:
        result == 'C VALUE'
    }

    private String doSomething(String str) {
        return str.toUpperCase()
    }
}
在本例中,
a
b
在每次测试之前设置,而
c
在执行任何规范之前只设置一次(这就是为什么它需要
@Shared
注释以在执行之间保持其值)

当我们运行此测试时,将在控制台中看到以下输出:

This method is executed only one time before all other specifications
This method is executed before each specification
This method is executed before each specification
This method is executed before each specification
This method is executed before each specification
一般的经验法则是,在
setupSpec
方法中设置
c
值后,您不应该更改它-主要是因为您不知道是否要执行哪个顺序测试(如果您需要保证顺序,您可以使用
@Stepwise
注释对类进行注释-Spock将按照在本例中定义的顺序运行所有案例)。在
a
b
的情况下,您可以在单个方法级别进行覆盖-它们将在执行另一个测试用例之前重新初始化。希望能有所帮助