2013-11-04 53 views
0

我修改了代碼從here看起來非常像我有的代碼,並試圖創建單元測試。雖然我會就像問一下「測試這個最好的方法是什麼」,我會很滿意的任何的方式來創建一個體面的單元測試!我查看了Spock,GroovyTestCase和GMock,而他們每個人都可以創建這樣的測試,我發現在所有情況下缺乏這樣一個示例的文檔。如何在Groovy中使用嵌套閉包進行單元測試(模擬類)?

class Searcher { 

    def http = new HTTPBuilder('http://ajax.googleapis.com') 

    def _executeSearch = { searchQ -> { 
      req -> 
      uri.path = '/ajax/services/search/web' 
      uri.query = searchQ 
      requestContentType = URLENC 
      response.success = { resp, reader -> 
       assert resp.statusLine.statusCode == 200 
       reader.text 
      } 
      response.failure = { resp -> println "FAILURE! ${resp.properties}" 
           resp.statusLine.statusCode } 
     } 
    } 

    def executeSearch(query) { 
     // http.setHeaders(Accept: 'application/json') // I want JSON back, but this not important 
     http.request(GET, _executeGetCommand(query)) 
    } 
} 

我想要什麼/需要做的就是以這樣的方式來嘲笑「HTTP」,我可以測試:

1. uri.query is getting properly set via the passed in data 
2. calls to response.success return mocked test data 
3. calls to failure get executed and return the failure code 

我可能接近這個完全不正確,將是開放的「正確的方式「去進行單元測試這樣的代碼。請忍受我,雖然這對我來說是新的!

+0

決定使用'spock'是一個明智的決定。你還在Spock中試過了什麼? – dmahapatro

+0

搞笑,我以爲你會說這是一個「非常合乎邏輯」的決定 - 哈哈。沒有嘗試過任何東西,因爲我發現的每個例子都是基本上微不足道的東西,無法像上面那樣找到任何示例規範。 – JoeG

回答

0

我會使用Spock mock作爲測試用例。它們應該很直接,因爲在單元測試期間不需要任何實際的網絡交互。

斯波克嘲笑在 the new spock docs

記錄還算不錯。如果你想從客戶端測試Web服務,看看創業板,作爲一個同伴斯波克效果很好。 Geb在the Book of Geb中有記錄。通過Web進行集成測試顯然涉及更多移動部分,因此您開始嘲笑服務器端是正確的。

相關問題