【问题标题】:How to Unit Test (mock class) in Groovy with nested closures?如何使用嵌套闭包在 Groovy 中进行单元测试(模拟类)?
【发布时间】:2013-11-04 20:57:24
【问题描述】:

我修改了 here 的代码,使其看起来非常像我拥有的​​代码,并且正在尝试为其创建单元测试。虽然我喜欢问“什么是最好的方法”来测试它,但我会很满意任何方法来创建一个体面的单元测试!我查看了 Spock、GroovyTestCase 和 GMock,虽然它们中的每一个都可能非常有能力创建这样的测试,但我发现在所有情况下都缺少此类示例的文档。

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

我可能完全错误地处理了这个问题,并且愿意接受对此类代码进行单元测试的“正确方式”。请耐心等待,因为这对我来说是新的!

【问题讨论】:

  • 决定使用spock 是一个明智的决定。您在 spock 中尝试过什么?
  • 有趣,我以为你会说这是一个“非常合乎逻辑”的决定——哈哈。没有尝试过任何东西,因为我发现的每个示例基本上都是微不足道的,并且找不到像上面这样的远程示例规范。

标签: unit-testing groovy spock gmock


【解决方案1】:

我会为您的测试用例使用 Spock 模拟。它们应该非常简单,因为您在单元测试期间不需要任何实际的网络交互。

Spock 模拟在 the new spock docs

如果您确实想从客户端测试 Web 服务,请查看 geb,它可以很好地与 spock 配合使用。 Geb 记录在 the Book of Geb 网络上的集成测试显然涉及更多的移动部分,因此您可以从模拟服务器端开始。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多