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

Mas*_*asa 8 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()

  }  
}  
Run Code Online (Sandbox Code Playgroud)

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

  }  
}     
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

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

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()
  }  
}
Run Code Online (Sandbox Code Playgroud)

Art*_*ero 23

在Spock中,存储在实例字段中的对象不在要素方法之间共享.相反,每个要素方法都有自己的对象.

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

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

    def "test if myMethod returns true"() {       
        expect:
          Result == true  
        where: 
          Result =  obj.myMethod()
    }
}
Run Code Online (Sandbox Code Playgroud)
class MyTest extends Specification {
    @Shared obj

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

    def "test if myMethod returns true"() {       
        expect:
          Result == true  
        where: 
          Result =  obj.myMethod()
    }
}
Run Code Online (Sandbox Code Playgroud)

设置环境有两种固定方法:

def setup() {}         // run before every feature method
def setupSpec() {}     // run before the first feature method
Run Code Online (Sandbox Code Playgroud)

我不明白为什么第二个例子setupSpec()有效并失败,setup()因为在文档中说不然:

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

  • 你有什么不明白的?@Shared字段_is_在要素方法之间共享,应使用字段初始值设定项或`setupSpec`方法进行设置.`setup`在这里不是一个好选择,因为它在`where`块被评估之后被调用. (5认同)