【问题标题】:Spock unit test, groovy leftshift assignment is throwing a SpockExecutionException: Data provider has no dataSpock 单元测试,groovy leftshift assignment 抛出 SpockExecutionException: Data provider has no data
【发布时间】:2015-09-28 14:09:11
【问题描述】:

我正在编写一个 spock 单元测试,当我尝试使用 groovy collect 动态提供数据提供者时,我得到了以下错误

SpockExecutionException: Data provider has no data

这是我能提供的最简单的引发错误的情况:

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

class SampleTest extends Specification {

    @Shared
    def someArray

    void setup() {
        someArray = ['a','b','c']
    }

    def "ensure that 'Data provider has no data' is not thrown"() {

        expect:
        columnA == columnB

        where:
        [columnA, columnB] << someArray.collect { value -> [value, value] }
    }
}

groovy 代码似乎可以工作。这是我在 groovy 控制台上的测试:

def someArray = ['a','b','c']
def test = someArray.collect { value -> [value, value] }
println test

[[a, a], [b, b], [c, c]]

我误会了什么?

我正在使用:

  • groovy 版本 2.2.1
  • spock 版本 0.7-groovy-2.0
  • junit 版本 4.12

【问题讨论】:

    标签: java unit-testing groovy junit spock


    【解决方案1】:

    使用setupSpec() 而不是setup() 以您想要的方式访问@Shared 变量,如@Shared documentation 中所示。或者,您也可以在共享变量的声明期间对其进行初始化。

    import spock.lang.*
    
    class SampleTest extends Specification {
    
        @Shared someArray
    
        // This is similar to just using
        // @Shared someArray = ['a','b','c']
        // Use above instead of setupSpec() if required
        // setupSpec() is invoked before any test case is invoked
        void setupSpec() {
            someArray = ['a','b','c']
        }
    
        def "ensure that 'Data provider has no data' is not thrown"() {
            expect:
            columnA == columnB
    
            where:
            [columnA, columnB] << someArray.collect { [it, it] }
        }
    }
    

    【讨论】:

    • 非常感谢@dmahapatro。我非常感谢您的及时回复。我还添加了指向共享注释文档的链接,答案就在那里,只要我读过它。 :)
    • 谢谢,没问题。 Spock(和一般的 Groovy)永远不会停止娱乐。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 2017-04-06
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多