使用Spock对Groovy2.0进行单元测试:setup()

时间:2012-01-31 18:18:39

标签: groovy gradle spock

我正在使用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:无法在null对象上调用方法myMethod()

以下是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()
  }  
}

1 个答案:

答案 0 :(得分: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()失败,因为在documentation中另有说明:

  

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

相关问题