分享

集合用toString()强转成String取值各种报错

 _bolo 2017-03-22
       
       当使用List、Map等集合时,取值给对象时,一定要特别注意,循环输出集合对象。

Q1.错误代码片段:

    debug时,鼠标移至对象名上面,可查看到取值情况,上述代码取到的值是[cssSelector]”,把集合类型直接强转成String类型输出,这时,当然取不到正确的值;如下:
 


Q2.在使用ExcelReader读取excel文件内容时,存在有空的值
看这段报错信息,
             org.openqa.selenium.NoSuchElementException: 

分析:     
          当excel存在多行数据,有一列有完整的值(图中“ExchangeDate”列),其余行空白格默认为空值存储。

 
     当代码读取到“International”时,看似只有一个值“English”,实际还有5行空数据,紧接着循环取值给findElement()的时候就会报错,找不到对应的element。
webDriver.findElement(By.xpath(expression)).click();

Q3.封装方法返回List<String>,当直接使用toString()取值给String字符串类型时,会出现如下情况:

Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"link text","selector":"[English]"}
For documentation on this error, please visit: http:///exceptions/no_such_element.html
Build info: version: '2.45.0', revision: '5017cb8e7ca8e37638dc3091b2440b90a1d8686f', time: '2015-02-27 09:10:26'
System info: host: 'Sunny-PC', ip: '172.27.216.1', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_67'
Driver info: driver.version: unknown

<anonymous class>.FirefoxDriver.prototype.findElementInternal_(file:///C:/Users/g/AppData/Local/Temp/anonymous402472970410245538webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:10271)
<anonymous class>.fxdriver.Timer.prototype.setTimeout/<.notify(file:///C:/Users/g/AppData/Local/Temp/anonymous402472970410245538webdriver-profile/extensions/fxdriver@googlecode.com/components/driver-component.js:603)


分析:
          代码取到的值会默认加上一对“[ ]”,因为List<String>是一个集合,非String强类型,直接用exofactory.getAppDatas("International").toString();获取到的是集合String的值,eclipse看上去也不报错,但是,它是一个集合的值,集合相当于是一个存储空间,里面有多维空间可以存地址或数据。
           当你需要获取集合所包含类型的值时,则需要通过循环或迭代出来集合里面存储的String类型值,才是正确的。

for (Iterator iterator = exofactory.getAppDatas("International").iterator(); iterator.hasNext();) {
String type = (String) iterator.next();
System.out.println(type);
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多