8

我正在使用 Spock 为 groovy-2.0 编写单元测试,并使用 gradle 运行。如果我在测试通过之后写。

import spock.lang.Specification

class MyTest extends Specification {  

  def "test if myMethod returns true"() {       
    expect:
      Result == true;   
    where: 
      Result =  new DSLValidator().myMethod()

  }  
}  

myMethod() 是 DSLValidator 类中的一个简单方法,它只返回 true。

但是,如果我编写 setup() 函数并在 setup() 中创建对象,我的测试将失败:Gradel 说:FAILED: java.lang.NullPointerException: Cannot invoke method myMethod() on null object

以下是 setup() 的样子,

import spock.lang.Specification

class MyTest extends Specification {  

  def obj

  def setup(){
   obj =  new DSLValidator()
  }

  def "test if myMethod returns true"() {       
    expect:
      Result == true;   
    where: 
      Result =  obj.myMethod()

  }  
}     

有人可以帮忙吗?

这是我遇到的问题的解决方案:

import spock.lang.Specification

class DSLValidatorTest extends Specification {

  def validator

  def setup() {
    validator = new DSLValidator()
  }


  def "test if DSL is valid"() { 

      expect:
        true == validator.isValid()
  }  
}
4

1 回答 1

23

在 Spock中,存储在实例字段中的对象不会在特性方法之间共享。相反,每个特征方法都有自己的对象。

如果您需要在功能方法之间共享对象,请声明一个@Shared字段

class MyTest extends Specification {
    @Shared obj = new DSLValidator()

    def "test if myMethod returns true"() {       
        expect:
          Result == true  
        where: 
          Result =  obj.myMethod()
    }
}

class MyTest extends Specification {
    @Shared obj

    def setupSpec() {
        obj = new DSLValidator()
    }

    def "test if myMethod returns true"() {       
        expect:
          Result == true  
        where: 
          Result =  obj.myMethod()
    }
}

有两种设置环境的夹具方法:

def setup() {}         // run before every feature method
def setupSpec() {}     // run before the first feature method

我不明白为什么第二个示例setupSpec()有效且失败,setup()因为文档中另有说明:

注意: setupSpec() 和 cleanupSpec() 方法可能不引用实例字段。

于 2012-01-31T20:56:44.267 回答