[英]Unable to call a groovy closure
我正在使用ws-lite自动执行Web服务测试,并且希望对生成的xml请求具有更灵活的控制。
基本上,请求正文是一个常规的闭包,将传递给MarkupBuilder以创建SOAP消息。
这是我要实现的示例(示例取自https://github.com/jwagenleitner/groovy-wslite ):
@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.0')
import wslite.soap.*
def client = new SOAPClient('http://www.holidaywebservice.com/Holidays/US/Dates/USHolidayDates.asmx')
def month = ["Feb"]
def response = client.send(SOAPAction:'http://www.27seconds.com/Holidays/US/Dates/GetMothersDay') {
body {
GetMothersDay('xmlns':'http://www.27seconds.com/Holidays/US/Dates/') {
year(2011)
month.each{ a = null ->
if (a != null){
"month"(a)
}
}
}
}
}
assert "2011-05-08T00:00:00" == response.GetMothersDayResponse.GetMothersDayResult.text()
assert 200 == response.httpResponse.statusCode
assert "ASP.NET" == response.httpResponse.headers['X-Powered-By']
在上面的示例中,我可以使用指定的一个或多个值创建月份标签。
但是,如果我将其更改为:
@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.0')
import wslite.soap.*
def client = new SOAPClient('http://www.holidaywebservice.com/Holidays/US/Dates/USHolidayDates.asmx')
def month_cl = { a -> "month"(a) }
def response = client.send(SOAPAction:'http://www.27seconds.com/Holidays/US/Dates/GetMothersDay') {
body {
GetMothersDay('xmlns':'http://www.27seconds.com/Holidays/US/Dates/') {
year(2011)
month_cl("Feb")
}
}
}
assert "2011-05-08T00:00:00" == response.GetMothersDayResponse.GetMothersDayResult.text()
assert 200 == response.httpResponse.statusCode
assert "ASP.NET" == response.httpResponse.headers['X-Powered-By']
我将缺少一个方法异常。
我不太明白为什么我不能只调用像这样的常规闭包?
必须将month_cl
关闭的委托设置为当前/父委托(在这种情况下,它作为参数传递给GetMothersDay
)。 尝试:
body {
GetMothersDay('xmlns':'http://www.27seconds.com/Holidays/US/Dates/') {
year(2011)
month_cl.delegate = delegate
month_cl("Feb")
}
}
获取MissingMethodException
是很正常的,因为闭包month_cl
正在调用不存在的month
方法。 为此(以您的方式),应将Closure c
传递给month_cl
并在参数a
上调用它,如下所示:
def month_cl = { a, Closure c -> c(a) }
并使用新的实现, month_cl("Feb")
变为month_cl("Feb") { "month" }
,结果为"month"("Feb")
。
这是一个工作示例:
@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.0')
import wslite.soap.*
def client = new SOAPClient('http://www.holidaywebservice.com/Holidays/US/Dates/USHolidayDates.asmx')
def months = ["Feb"]
def month_cl = { m, Closure c -> return c(m) }
def response = client.send(SOAPAction:'http://www.27seconds.com/Holidays/US/Dates/GetMothersDay') {
body {
GetMothersDay('xmlns':'http://www.27seconds.com/Holidays/US/Dates/') {
year(2011)
month_cl("Feb") { "month" } // -> month("Feb")
}
}
}
assert "2011-05-08T00:00:00" != response.GetMothersDayResponse.GetMothersDayResult.text()
assert 200 == response.httpResponse.statusCode
assert "ASP.NET" == response.httpResponse.headers['X-Powered-By']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.