2014-03-13 144 views
1

我寫了這個簡單的服務通過HTTPBuilder做子請求,以獲得代表取得的頁進一步使用類的實例:如何在Grails(Spock)中模擬服務器進行單元測試?

package cmspage 

import groovyx.net.http.HTTPBuilder 
import static groovyx.net.http.Method.GET 
import static groovyx.net.http.ContentType.HTML 

class CmsPageService { 
    static transactional = false 
    final String SUBREQUEST_HOST = "www.mydomainforsubrequest.com" 

    CmsPage getCmsPageInstance(Object request) { 
     String host = request.getServerName() 
     String url = request.getRequestURI() 
     HashMap queryMap = this.queryStringToMap(request.getQueryString()) 
     return this.subRequest(host, url, queryMap) 
    } 

    CmsPage getCmsPageInstance(String host, String url, String queryString = null) { 
     HashMap queryMap = queryStringToMap(queryString) 
     return this.subRequest(host, url, queryMap) 
    } 

    private CmsPage subRequest(String host, String url, HashMap queryMap = null) { 
     CmsPage cmsPageInstance = new CmsPage() 
     HTTPBuilder http = new HTTPBuilder() 
     http.request("http://" + SUBREQUEST_HOST, GET, HTML) { req -> 
      uri.path = url 
      uri.query = queryMap 
      headers.'X-Original-Host' = 'www.mydomain.com' 
      response.success = { resp, html -> 
       cmsPageInstance.responseStatusCode = resp.status 
       if (resp.status < 400) { 
        cmsPageInstance.html = html 
       } 
      } 
      response.failure = { resp -> 
       cmsPageInstance.responseStatusCode = resp.status 
       return null 
      } 
     } 
     return cmsPageInstance 
    } 

    private HashMap queryStringToMap(String queryString) { 
     if (queryString) { 
      queryString = queryString.replace("?", "") 
      String[] splitToParameters = queryString.split("&") 
      HashMap queryMap = new HashMap() 
      splitToParameters.each { 
       String[] split = it.split("=") 
       for (int i = 0; i < split.length; i += 2) { 
        queryMap.put(split[i], split[i + 1]) 
       } 
      } 
      return queryMap 
     } else return null 
    } 
} 

現在我需要編寫單元測試這項服務。我想使用一些簡單的html文檔來測試它,而不是測試一些「實時」網站。但是我不知道怎麼做? 任何人都可以幫助我嗎?

+0

http://stackoverflow.com/questions/9101084/groovy-httpbuilder-mocking-the-response –

回答

相關問題