请原谅,如果这是一个 n00b 问题,我是 grails 的 n00b ......
我已经使用 grails install-plugin rest
安装了“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 结果。此代码按预期工作。它通过 Controller 工作。它甚至可以通过集成测试通过 Controller 工作。这是我的单元测试:
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/], ...]
因此,似乎在测试运行时,插件未处于事件状态。我没有对插件进行任何额外的配置。我真的不明白为什么测试环境应该以不同的方式编译这个类。
我的意图是一旦开始就模拟网络接口(interface),因为它具有外部依赖项。但我是一步一步来的。
我需要注入(inject)模拟
withRest()
甚至运行测试?还是有其他问题?谢谢!
最佳答案
这就是单元测试的工作方式。没有插件处于事件状态,没有 Spring、Hibernate 等。您只是在运行一个类,因此必须模拟所有内容。不过,似乎 REST 不是模拟的糟糕候选者,从那时起你就只是在测试模拟。
我可能会用功能测试来测试它。不幸的是,这不如单元测试方便,但糟糕的测试并不是很有用:) 您可以对其进行配置,以便在配置中查找 url 以允许使用不同的 URL 进行测试,这样您就不需要访问外部服务,然后设置一个真正的 REST 服务来进行返回已知值的测试。
关于rest - 带有休息插件的 Grails (2.0.3) 有效!但是单元测试失败了。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11043230/