2014-09-24 102 views
0

我想寫單位爲我的Grails服務方法之一,單元測試就像是Grails-斯波克:打開設置方法,常用的方法

@Shared instance1, instance2, instance3 
class testClass extends Specification { 
def setup() { 
    // initaiting some value here 
    instance1 = new Initate(one:"one") 
    instance2 = new Initate(one:"one") 
    instance3 = new Initate(one:"one") 
} 

def "testmethodcall"() { 
     //testsetup() 

     when: 
     def result = someMethod(value1) // Here is the error 

     then: 
      result==value2 
     where: 
     value  | value1  | value2 
     instance1 | instance2 | instance3 

    } 
} 

出於某種原因,我們打算提出這裏面的代碼設置方法的另一種方法,並打算調用它是必需的,這樣

@Shared instance1, instance2, instance3 

class testClass { 
def testsetup() { 
    // initialize the code what we initialize in setup 
    // initaiting some value here 
    instance1 = new Initate(one:"one") 
    instance2 = new Initate(one:"one") 
    instance3 = new Initate(one:"one") 
} 


def "testmethodcall"() { 
     testsetup() 

     when: 
     def result = someMethod(value1) // Here is the error 

     then: 
      result==value2 

     where: 
     value  | value1  | value2 
     instance1 | instance2 | instance3 

    } 
} 

截至目前它是好的,方法調用工作正常,甚至變量進行了初始化,但是當我嘗試使用數據列值是返回空值,但是當我更改爲setup()方法我得到真正的價值。有人可以解釋我,我怎麼能能夠改變setUp方法normal method

+0

我在這裏遇到spock的奇怪行爲 – 2014-09-24 14:08:08

回答

0

有幾件事情需要記下: -

  1. 設置() - 用於與每個測試用例運行
  2. setupSpec() - 被用於一次一個測試類/單元
  3. 共享運行 - 可見throughout.And因此必須一次初始化,因此必須在當在setupSpec工作和不內設置。
  4. cleanup() - 與每個測試用例一起運行
  5. cleanupSpec - 在所有測試用例運行後的最後一次運行。
  6. 只有@Shared和靜態變量可以從其中內訪問:塊。
  7. 單獨的輸入和輸出與預期的雙管||

除了這些,在你的代碼testmethodcall方法有語法錯誤。

  1. 沒有比較完成
  2. 期待:缺少
  3. 爲什麼Def值是存在的,而我們使用數據表變量會自動聲明 此外,值2沒有使用其中

而且,你說,你是能夠與上面的代碼成功運行測試用例時設置()方法是存在的,它只是默默地傳遞無失敗既是值和值1爲空。

下面是你的代碼的修改版本


def "test methodcall"(){ 
setup() 
     expect: 
     value == someMethod(value1) // Here is the error 

     println '----instance1----'+value 
     println '----instance2----'+value1 
     println '----instance1----'+instance1 
     println '----instance2----'+instance2 
//  instance1 == instance2 
     where: 
     value  | value1 
     instance1 | instance2 
    } 

現在看到的println輸出,你會明白這issue.Hope會得到你的答案。

+0

感謝您的回答,無論如何是錯字錯誤,您可以看到我的編輯問題 – 2014-09-25 10:41:32

+0

好了!您已經使用when:then:而不是expect:now.So現在工作? – 2014-09-25 10:50:51

+0

我更新了問題,但答案保持不變 – 2014-09-25 18:08:55

相關問題