2012-01-31 80 views
8

我正在使用Spock为groovy-2.0编写单元测试,并使用gradle来运行。如果我在测试通过后写下。使用Spock进行单元测试Groovy2.0:setup()

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。

但是,如果我写的设置()函数创建设置()的对象,我的测试失败:格拉德尔说:失败:显示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() 
    } 
} 

回答

20

在斯波克对象存储的实例字段不是功能的方法之间共享。相反,每个要素方法都有自己的对象。

如果您需要在要素方法之间共享对象,则声明@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() 
    } 
} 

有2点设置环境夹具的方法:

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

我不明白为什么有setupSpec()作品的第二个例子和失败setup()因为documentation否则说:

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

+0

奇怪...... Spock文档可能会对此做出澄清......我不会说obj是在特征方法之间共享的,而是在每个fixture被调用之前设置的。 – 2012-01-31 21:18:06

+5

你不明白的是什么?要素方法之间共享@Shared字段_is_,并且应该使用字段初始值设定项或'setupSpec'方法进行设置。 'setup'在这里不是一个好的选择,因为在'where'块被评估之后它会被调用。 – 2012-02-01 15:25:09

+0

感谢您的澄清 – 2012-02-01 16:47:04