Grails-spock:将设置方法转换为普通方法

Grails-spock:将设置方法转换为普通方法,grails,spock,Grails,Spock,我试图为我的grails服务方法之一编写单元,单元测试如下 @Shared instance1, instance2, instance3 class testClass extends Specification { def setup() { // initaiting some value here instance1 = new Initate(one:"one") instance2 = new Initate(one:"one") instance3 = ne

我试图为我的grails服务方法之一编写单元,单元测试如下

@Shared instance1, instance2, instance3
class testClass extends Specification {
def setup() {
   // initaiting some value here
   instance1 = new Initate(one:"one")
   instance2 = new Initate(one:"one")
   instance3 = new Initate(one:"one")
}

def "testmethodcall"() {
       //testsetup()

       when:
       def result = someMethod(value1) // Here is the error

       then:
          result==value2
       where:
       value      | value1      |   value2
       instance1  | instance2   | instance3

    }
}
出于某种原因,我们计划将此设置方法中的代码移动到另一个方法,并计划在需要时调用它,如下所示

@Shared instance1, instance2, instance3

class testClass {
def testsetup() {
   // initialize the code what we initialize in setup
   // initaiting some value here
   instance1 = new Initate(one:"one")
   instance2 = new Initate(one:"one")
   instance3 = new Initate(one:"one")
}


def "testmethodcall"() {
       testsetup()

       when:
       def result = someMethod(value1) // Here is the error

       then:
          result==value2

       where:
       value      | value1      |   value2
       instance1  | instance2   | instance3

    }
}

现在一切正常,方法调用工作正常,甚至变量也已初始化,但当我尝试使用数据列值时,它返回空值,但当我更改为setup方法时,我得到了实际值。有人能给我解释一下,我怎样才能将设置方法更改为普通方法吗?

有几件事需要注意:-

设置-用于与每个测试用例一起运行 setupSpec-用于对测试类/单元运行一次 共享-始终可见。因此必须初始化一次,因此必须在setupSpec中处理,而不是在setupSpec中。 清理-与每个测试用例一起运行 cleanupSpec-在所有测试用例运行后最后运行。 在where:块中只能访问@Shared和static变量。 使用双管将输入和输出分开|| 除此之外,代码中的testmethodcall方法还有语法错误

没有进行比较 expect:是缺少的 为什么会有def值,而我们使用的是自动声明变量的数据表 此外,在任何情况下都不使用值2 此外,您还声明,当setup方法存在时,您能够使用上述代码成功运行测试用例,它只是默默地传递而没有失败,因为value和value1都为null

下面是代码的修改版本


现在查看println输出,您将了解问题。希望这能为您提供答案。

我在这里遇到了一个奇怪的斯波克行为感谢您的回答,不管怎样,这是打字错误,您可以查看我的编辑问题OK!您使用的是when:and then:而不是expect:now。那么它现在起作用了吗?我更新了问题,但答案保持不变
def "test methodcall"(){
 setup()
        expect:
        value == someMethod(value1) // Here is the error

        println '----instance1----'+value
        println '----instance2----'+value1
        println '----instance1----'+instance1
        println '----instance2----'+instance2
//        instance1 == instance2
        where:
        value      | value1
        instance1  | instance2
    }