2012-01-31 79 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