方法返回不正确的值

时间:2011-12-06 04:10:16

标签: groovy selenium iteration return-value

如果我调用findEventWithStatus(“Comment”,“Completed”)而不是返回单个事件,它将返回getEvents()方法生成的整个事件列表。为什么会这样?适用的代码如下。

Event对象的定义: -

class Event {
    String description
    String date
    String status
    WebElement editEvent
    WebElement deleteEvent
}

使用selenium从HTML表中获取事件: -

def getEvents() {
    def eventSize = driver.findElements(By.xpath('//div[@id[contains(.,"eventsReviewTable")]]/table/tbody/tr')).size()
    def eventList = new ArrayList()
    def event = new Event()
    def x
    for (y in 0..eventSize-1) {
        x = (y+1).toString()
        event.date = driver.findElement(By.xpath("//div[@id[contains(.,'eventsReviewTable')]]/table/tbody/tr["+ x + "]/td[1]/div/span")).getText()
        event.description = driver.findElement(By.xpath("//div[@id[contains(.,'eventsReviewTable')]]/table/tbody/tr["+ x + "]/td[2]/div/span")).getText()
        event.status = driver.findElement(By.xpath("//div[@id[contains(.,'eventsReviewTable')]]/table/tbody/tr["+ x + "]/td[4]/div/span")).getText()
        event.editEvent =  driver.findElement(By.xpath("//div[@id[contains(.,'eventsReviewTable')]]/table/tbody/tr["+ x + "]/td[6]/div/a[@id[contains(.,'editEventLink')]]"))
        event.deleteEvent =  driver.findElement(By.xpath("//div[@id[contains(.,'eventsReviewTable')]]/table/tbody/tr["+ x + "]/td[6]/div/a[@id[contains(.,'deleteEventLink')]]"))
        eventList.add(event)
        event = new Event()
    }
    return eventList
}

查找具有特定状态和说明的活动: -

def findEventWithStatus(String desc, String status) {
    def events = getEvents()
    events.each() {
        if(it.description == desc && it.status == status) {
             return it
        }
    }
}

1 个答案:

答案 0 :(得分:1)

问题是return it方法中的findEventWithStatus从传递给event.each的闭包返回,而不是从findEventWithStatus方法返回。所以,each方法没有做任何事情,并且当each返回调用它的集合时,它返回events值,这是最终从findEventWithStatus events.each { ... }是该方法中的最后一个语句。我希望这不会让他感到困惑。

无论如何,可以使用for语句而不是each来修复它,但是,当您搜索对象时,find方法会更好用:

def findEventWithStatus(String desc, String status) {
    getEvents().find { it.description == desc && it.status == status }
}