对于测试用例,未定义可变外部本地范围

时间:2018-06-18 17:13:02

标签: groovy

我希望在Groovy中访问我正在编写的测试函数的外部变量。

然而,我似乎无能为力。

我的代码是这样的:

Map<String, String> originalTableRowState = new HashMap<String, String>(),
    newTableRowState

// if there is table data to get, and do actions on
def WebDriver driver = DriverFactory.getWebDriver()
def List<WebElement> dataRows = driver.findElements(
    By.cssSelector('div.tab-pane.active .dataTables_scrollBody tbody tr:not(.dataTables_empty)'))   

'if there\'s table data, this test should run'
if (dataRows.size() > 0) {

    WebUI.comment('populate the tableRowState with the data from the first table row')
    fetchFirstRowDataInto(originalTableRowState)    

}


void fetchFirstRowDataInto(Map<String, String> tableRowState) { 
    List<WebElement> tableHeadings = driver.findElements(
        By.cssSelector('div.tab-pane.active .dataTables_scrollHead th'))
    WebElement firstRow = dataRows.get(0)
    List<WebElement> dataCells = firstRow.findElements(
        By.xpath('//td[not(@class="dataTables_empty") and not(*)]'))
    for (int i = 0; i < dataCells.size(); i++) {
        // save data to originalTableRowState with the table header text as the key
        tableRowState.put(tableHeadings.get(i), dataCells.get(i))
    }
}

当我运行它时,它会以Variable 'driver' is not defined outside test case的错误向我致意。我刚刚将def个关键字添加到driverdataRows定义中。

如何在函数内部访问driverdataRows,而不将它们作为参数传递?

1 个答案:

答案 0 :(得分:0)

我通过声明类似JS的闭包来修复方法变量访问问题:

/ *将void fetchFirstRowDataInto(Map<String, String> tableRowState) {更改为def fetchFirstRowDataInto = { Map<String, String> tableRowState -> * /

并将定义置于之上。

我欢迎任何更好的解决方案......