[英]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.