1

请原谅,如果这是一个 n00b 问题,我是 grails 的 n00b ......

我已经使用grails install-plugin rest.

我的服务类有这个代码(编辑):

def index() {
  def data

  withRest(uri:'http://localhost:8090/some/valid/url/running/here/') {
    auth.basic 'admin', 'admin'
    def response = get(path: 'something', query: [format: 'json'])
    data = response.data
  }
  return data
}

如果我运行grails console,实例化我的服务类并调用service.index(),我会得到预期的 JSON 结果。此代码按预期工作。它通过控制器工作。它甚至可以通过集成测试通过控制器工作。

这是我的单元测试:

void testIndex() {
    def response = service.index()
    assertEquals(response.total, 2)
    assertEquals(response.receipts.size, 2)
    assertEquals(response.receipts.collectEntries{ [it.id, [id: it.id]] }, [1: [id:1], 2:[id:2]])
}

这失败并出现错误:

groovy.lang.MissingMethodException: No signature of method: torch.ReceiptService.withRest() is applicable for argument types: (java.util.LinkedHashMap, torch.ReceiptService$_index_closure1) values: [[uri:http://localhost:8090/some/valid/url/running/here/], ...]

因此,似乎在测试运行时,插件未处于活动状态。我没有对插件进行任何额外的配置。我真的不明白为什么测试环境应该以不同的方式编译这个类。

我的意图是一旦开始就模拟网络接口,因为它具有外部依赖项。但我是一步一步来的。

我是否需要注入一个模拟withRest()来运行测试?还是有其他问题?

谢谢!

4

1 回答 1

5

这就是单元测试的工作方式。没有插件处于活动状态,没有 Spring、Hibernate 等。您只是在运行一个类,因此必须模拟所有内容。似乎 REST 不是模拟的糟糕候选者,从那时起你就只是在测试模拟。

我可能会用功能测试来测试它。不幸的是,这不如单元测试方便,但糟糕的测试不是很有用:) 您可以对其进行配置,以便在配置中查找 url 以允许使用不同的 URL 进行测试,这样您就不需要访问外部服务,然后设置一个真正的 REST 服务用于返回已知值的测试。

于 2012-06-15T02:16:08.983 回答