如何在Grails(Spock)中模拟服务器进行单元测试?

时间:2014-03-13 14:56:57

标签: unit-testing grails service groovy spock

我已经编写了这个简单的服务,通过HTTPBuilder进行子请求,获取代表获取页面的类实例以供进一步使用:

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文档来测试它,而不是测试一些“实时”网站。但是我不知道怎么做? 有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

Jadler应该适合你。检查其文档和post on basic usage