前言
在做Android自动化测试的时候,使用@AndroidFindBy注解标记element的时候发现对象的hashcode会变,找时间稍微看了下,在这做一个笔记
问题
首先看下遇到的问题:
@AndroidFindBy(className = "android.widget.EditText")
private List<MobileElement> checkCodes;
public int test() throws Exception {
for (MobileElement mobileElement : checkCodes) {
if (2 == Integer.parseInt(mobileElement.getText())) {
return checkCodes.indexOf(mobileElement);
}
}
throw new Exception("未找到验证码2!");
}
手机界面
可以看出,是在定位“2”的位置,但是代码运行起来后,test方法返回的是-1
从test方法看,方法要么返回大于0的数,要么抛出异常,不会返回-1的
原因
我在每次循环的时候打印了每个元素的ID
public int test() throws Exception {
List<String> tempList = new ArrayList<>();
for (MobileElement mobileElement : checkCodes) {
tempList.add(checkCodes.get(0).getId());
if (2 == Integer.parseInt(mobileElement.getText())) {
tempList.forEach(n -> System.out.println(n));
return checkCodes.indexOf(mobileElement);
}
}
throw new Exception("未找到验证码2!");
}
输出:
我每次都拿的list的第一个元素,但是三次循环的时候打印出来的element的ID都不同,list已经不是原来的list了,所以返回-1就可以理解了
接下来我在调试的时候截图:
可以看到,每次循环的时候,list里面element的hashcode的值都不同的。原来,是因为我们的控件是使用注解@AndroidFindBy来获取的,如果使用如下方式来获取,就不存在这个问题
List<MobileElement> checkCodes = driver.findElements(By.className("android.widget.EditText"));
但是使用注解有很多好处,以后会谈,今天先看当前的问题
只想解决问题,看到这就可以了,下面是深入研究
注解
简单点的就可以理解为标签。比如@AndroidFindBy,可以用于注解element
他的属性(可以理解为他的属性)有uiAutomator,accessibility,id,className,tagName,xpath和priority,都是有默认值的。我在这里把他的className属性设置为了“android.widget.EditText”,在反射中需要用到
(未完)