自动化测试中用到的一些功能类

发表于:2013-9-09 11:00

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Kiven_Test    来源:51Testing软件测试网采编

  1、WebDriver处理一些弹窗

import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class AlertOperate {
 static WebDriver dr = new InternetExplorerDriver();
 
 public static void main(String args[]) throws InterruptedException{
  dr.get("www.baidu.com");
  
  dr.findElement(By.id("lb")).click();
  
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  tanchukuang();
 }
 
 
 //处理潜在的1个alert(javascript弹出框)
 public boolean dealPotentialAlert(WebDriver driver,boolean option) {
  boolean flag = false;
  try {
   Alert alert = driver.switchTo().alert();
   if (null == alert)
    throw new NoAlertPresentException();
   try {
    if (option) {
     alert.accept();
     System.out.println("Accept the alert: " + alert.getText());
    } else {
     alert.dismiss();
     System.out.println("Dismiss the alert: " + alert.getText());
    }
    flag = true;
   } catch (WebDriverException ex) {
    if (ex.getMessage().startsWith("Could not find"))
     System.out.println("There is no alert appear!");
    else
     throw ex;
   }
  } catch (NoAlertPresentException e) {
   System.out.println("There is no alert appear!");
  }
  return flag;
 }
 
 //处理非JS弹窗
 public static boolean testNewWindow(){
  //当前窗口句柄
   String currentHandle = dr.getWindowHandle();
  //得到所有窗口的句柄
   Set<String> handles = dr.getWindowHandles();
   handles.remove(currentHandle);
   if (handles.size() > 0) {
    try{
     dr.switchTo().window(handles.iterator().next());
     //dr.switchTo().window(dr.getWindowHandles().iterator().next());
     return true;
    }catch(Exception e){
     System.out.println(e.getMessage());
     return false;
    }
   }
   System.out.println("Did not find window");
   return false;
 }
 
 //一般弹出窗口
 public static void tanchukuang() throws InterruptedException{
  //得到所有窗口
  Set<String> allWindowsId = dr.getWindowHandles();
  //通过查找页面内容得到新的窗口
  for(String windowId : allWindowsId){
   dr.switchTo().window(windowId);
   Thread.sleep(1000);
   dr.findElement(By.id("TANGRAM__PSP_10__userName")).sendKeys("test");
   
   //第一个按钮是确定按钮
   //dr.findElement(By.xpath("//button[@type='button']")).click();
   //System.out.println(dr.switchTo().window(windowId).getTitle());
   break;
  }
 }
 
}

51/512345>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号