【问题标题】:Run specific Spock Tests without setup?在没有设置的情况下运行特定的 Spock 测试?
【发布时间】:2018-02-02 10:13:54
【问题描述】:

documentationSpock 的“夹具方法”部分中提到了这些功能:

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 函数为所有测试初始化​​新对象。然而,一些测试应该测试当还没有其他对象时会发生什么。

由于设置,这些测试现在失败了。

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

或者我是否必须创建一个单独的“设置”函数并在我所做的每个测试中调用它们。大多数测试都使用它!

【问题讨论】:

    标签: testing spock


    【解决方案1】:

    您始终可以仅针对该特定方法覆盖测试方法中的值。看看下面的例子:

    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()
        }
    }
    

    在此示例中,ab 在每次测试之前设置,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
    

    一般的经验法则是,在 c 方法中设置了 c 值后,您不应该更改它 - 主要是因为您不知道是否要执行哪个订单测试(如果您需要保证您可以使用 @Stepwise 注释来注释您的类的顺序 - Spock 将按照在这种情况下定义的顺序运行所有案例)。在ab 的情况下,您可以在单个方法级别覆盖 then - 它们将在执行另一个测试用例之前重新初始化。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-01-09
      • 2010-12-06
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      相关资源
      最近更新 更多