【问题标题】:String Array Method not Returning the Array Object - Selenium WebDriver字符串数组方法不返回数组对象 - Selenium WebDriver
【发布时间】:2013-03-30 11:02:46
【问题描述】:

请找到我的代码,它不返回数组对象值,它只返回一个数组对象

public String[] verify_userRole(String[] Expected_role) {
        String[] actual_role = new String[4];
        String first;
        WebElement role_table = driver.findElement(By
                .xpath("//*[@id='tblListView']/tbody[1]"));
        List<WebElement> allRows = role_table.findElements(By.tagName("tr"));

        for (WebElement row : allRows) {
            List<WebElement> cells = row.findElements(By.tagName("td"));

            for (WebElement cell : cells) {
                first = cell.getText().toString();
                actual_role = new String[] {first};

                }
        }
        return actual_role;
    }

变量首先包含四个值("name","name1","name2","name3") 将此字符串值转换为数组(实际角色)后,它只返回一个值(“名称”)

请说明上述代码的问题是什么

【问题讨论】:

    标签: java selenium-webdriver testng pageobjects


    【解决方案1】:

    您在循环中的每一步都重新初始化字符串数组。

    你应该只做一次。

       ArrayList<String> actual_role = new ArrayList<String>( )
       for (WebElement row : allRows) {
            List<WebElement> cells = row.findElements(By.tagName("td"));
    
            for (WebElement cell : cells) {
                first = cell.getText().toString();
                actual_role.add(first);
    
            }
        }
    
        return (String[]) actual_role.toArray( new String[ actual_role.size() ] );
    

    顺便说一句,我已将您的示例转换为使用中间 ArrayList,因为您不知道实际数据大小,并且动态重新初始化数组很容易出错。

    如果您正在实现的方法的签名不是由外部框架规定的,我建议您使用List&lt;String&gt; 作为返回类型而不是String[]。

    【讨论】:

      【解决方案2】:

      你总是在循环中实例化你的数组:

      actual_role = new String[] {first};
      

      试试吧:

      actual_role[i] = first;
      

      当 i 是当前索引时。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-09
        • 2016-08-28
        • 2018-08-12
        • 2012-07-22
        • 1970-01-01
        • 2014-07-30
        相关资源
        最近更新 更多