Groovy脚本:列表/地图集

时间:2017-11-03 21:15:41

标签: groovy

我已经创建了一个脚本,我用它来模拟SOAP UI中的SOAP服务(作为模拟服务)的行为以进行sprint测试,但在尝试迭代我创建的List时遇到问题。列表由许多地图组成,每个地图包含一个列表。看起来应该是这样的:

[[Rec: 1, Items: ["AB123","BC234","CD345"]],[Rec: 2, Items: ["AB123","BC234","CD345","DE456"]]]

这是我建立List的代码:

def offerMap      = [:] 
def outputList    = [] 
def offerItemList = [] 

def outputMap     = [:] 
def outList       = [] 

def item          = "" 
def rec           = "" 

offerItemList.add("AB123") 
offerItemList.add("BC234") 
offerItemList.add("CD345") 

offerMap.put("Rec",1) 
offerMap.put("Items",offerItemList) 

outputList.add(offerMap) 

log.info "OUT: outputList.size ${outputList.size()}" 
log.info "OUT: offerItemList.size ${offerItemList.size()}" 

offerMap.clear() 
offerItemList.clear() 

offerItemList.add("AB123") 
offerItemList.add("BC234") 
offerItemList.add("CD345") 
offerItemList.add("DE456") 

offerMap.put("Rec",2) 
offerMap.put("Items",offerItemList) 

outputList.add(offerMap) 

log.info "OUT: outputList.size ${outputList.size()}" 
log.info "OUT: offerItemList.size ${offerItemList.size()}" 

这是我必须遍历列表的代码:

outputList.each { 

    log.info "OUT: outputList.size ${outputList.size()}" 

    outputMap.clear() 
    outputMap = it 

    rec = outputMap.get("Rec") 
    log.info "OUT: REC ${rec}" 

    outList.clear() 
    outList = outputMap.get("Items") 

    outList.each { 

        item = it 
        log.info "OUT: Item ${item}" 

    } 
}

但这并没有给我我期望的结果。第一个问题是outputList.each循环似乎立即跳转到列表中的第二个条目,如输出中所见:

Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: outputList.size 1 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: offerItemList.size 3 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: outputList.size 2 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: offerItemList.size 4 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: outputList.size 2 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: REC 2 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: Item AB123 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: Item BC234 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: Item CD345 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: Item DE456 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: outputList.size 2 
Fri Nov 03 17:54:32 GMT 2017:INFO:OUT: REC null 

由于我缺乏Groovy的经验,我的想法已经不多了,而且我可能会遗漏一些基本的东西。

1 个答案:

答案 0 :(得分:0)

请考虑以下事项。请注意,目标并不完全清楚,但这是一个有根据的猜测(在您的示例中,RecRow也不清楚)。

def outputList = [
['Rec': 1, 'Items': ["AB123","BC234","CD345"]],
['Rec': 2, 'Items': ["AB123","BC234","CD345","DE456"]]
]

outputList.each { outputMap ->
    // is row == Rec ???
    def row = outputMap['Rec']
    println "OUT ROW: ${row}"

    def items = outputMap['Items']
    items.each { item ->
        println "OUT Item: ${item}"
    } 
}

输出:

$ groovy Example.groovy
OUT ROW: 1
OUT Item: AB123
OUT Item: BC234
OUT Item: CD345
OUT ROW: 2
OUT Item: AB123
OUT Item: BC234
OUT Item: CD345
OUT Item: DE456