在做界面自动化用例实现的过程中,经常会碰到鼠标点击不生效、滑块验证问题等,先将一些我自己用到的解决方法总结如下:
1、 鼠标单击事件
1.1 直接click
**.click()
1.2 先move,再click
鼠标单击,页面跳转
WebElement button=driver.findElement(By.xpath("//div[@id='4d91d1045aad48c4af47657c40d34f8d']/span[4]"));
Actions acttion=new Actions(driver);
acttion.moveToElement(button).perform();
Thread.sleep(1000);
acttion.click(button).perform();
1.3 通过javascript语句执行
WebElement eAction = driver.findElement(By.xpath(getStringByKeyName("MenuAction")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", eAction);
1.4 通过ENTER键代替click
WebElement element = driver.findElement(By.xpath("//a[@class='return']"));
Actions action = new Actions(driver);
action.contextClick(element).perform();
element.sendKeys(Keys.ESCAPE);
element.sendKeys(Keys.ENTER);
2、查看指定元素属性
System.out.println(obj_temp.isDisplayed());
3、上传一个文件附件
通过sendKeys方法上传一个文件附件
@FindBy(id = "btn_file")
public WebElement btn_upfile;//上传附件
serviceregister.btn_upfile.sendKeys("D:\\auto_test\\a.docx");
serviceregister.btn_nextBtn.click();
注意:该上传附件按钮在页面的javascript定义图示如下
4、 http请求服务接口模式
(1)post方式
……
os.write(req);
os.flush();
bis = new BufferedInputStream(conn.getInputStream());
int len = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] cache = new byte[8 * 1024];
while ((len = bis.read(cache)) != -1) {
baos.write(cache, 0, len);
}
baos.flush();
byte[] temp = baos.toByteArray();
baos.close();
……
(2)get方式
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setReadTimeout(readTimeout);
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[2048];
int len = -1;
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
is.close();
conn.disconnect();
conn=null;
baos.flush();
byte[] temp = baos.toByteArray();
baos.close();
5、登录滑块验证
int moveX =99;//移动位置
/*下面获取的滑块整体元素,目的获得总长度*/
WebElement element = driver.findElement(By.id("slider"));
Point location = element.getLocation();
element.getSize();
//执行时,这里的元素为滑块的可移动的元素
Actions action_1= new Actions(driver);
action_1.dragAndDropBy(btn_slider_drag, location.x+moveX,location.y).perform();
即绿框标注的元素为element,红框标注的元素为btn_slider_drag。