Java自动化测试构建(公共类方法封装)
程序员文章站
2022-04-15 18:50:33
思想和概念无限多,无需赘述,源码奉上,可无限扩展...
package Util; /** * 描述: * The method of common * * @author davieyang * @create 2018-08-05 0:37 */ import static Configurations.Constants.Path_BrowserDrivers; import static Util.LogUtil.info; import static Util.WaitElementUntil.waitWebElementPresence; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import Configurations.Constants; import org.apache.log4j.xml.DOMConfigurator; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import TestScripts.TestSuiteByExcel; public class KeyWordsAction { private static WebDriver driver; private static GetElementsUtil getElementsUtil = new GetElementsUtil(Constants.Path_ConfigurationFile); static { //指定log4j配置文件为log4j.xml DOMConfigurator.configure("log4j.xml"); } /** *定义函数initBrowser,并返回驱动, 参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ //方法名对应Excel文件中的“关键字”列中的open_browser关键字,Excel“操作值”列中的内容用于指定用何种浏览器,也就是本函数的参数 public static WebDriver open_browser(String browserName, String string) { if(browserName.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver",Path_BrowserDrivers + "chromedriver.exe"); driver = new ChromeDriver(); LogUtil.info("启动Chrome浏览器"); }else if (browserName.equalsIgnoreCase("ie")){ System.setProperty("webdriver.ie.driver",Path_BrowserDrivers + "IEDriverServer.exe"); driver = new InternetExplorerDriver(); LogUtil.info("启动IE浏览器"); }else { System.setProperty("webdriver.gecko.driver", Path_BrowserDrivers + "geckodriver.exe"); driver = new FirefoxDriver(); LogUtil.info("启动Firefox浏览器"); } return driver; } /** *定义函数navigate, 参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ //对应Excel文件中“关键字”列的navigate关键字 public static void navigate(String url, String string) { driver.get(url); LogUtil.info("访问" + url); } /** *定义函数input,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ //对应Excel文件中“关键字列”的input关键字 public static void input(String locatorExpression, String inputString) { System.out.println("收到用户名输入:" + inputString); try { driver.findElement(getElementsUtil.getLocator(locatorExpression)).clear(); LogUtil.info("清除" + locatorExpression + "输入框的所有内容"); driver.findElement(getElementsUtil.getLocator(locatorExpression)).sendKeys(inputString); LogUtil.info("在" + locatorExpression + "输入框中输入:" + inputString); } catch (Exception e) { TestSuiteByExcel.testResult = false; LogUtil.info("在" + locatorExpression + "输入框中输入" + inputString + "时出现异常,异常信息为:" + e.getMessage()); e.printStackTrace(); } } /** *定义函数click,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void click(String locatorExpression, String string){ try{ driver.findElement(getElementsUtil.getLocator(locatorExpression)).click(); LogUtil.info("点击" + locatorExpression + "页面元素成功"); }catch (Exception e){ TestSuiteByExcel.testResult = false; LogUtil.info("单击" + locatorExpression + "页面元素出现异常,异常信息为:" + e.getMessage()); e.printStackTrace(); } } /** *定义函数WaitFor_Element,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void WaitFor_Element(String locatorExpression, String string){ try{ waitWebElementPresence(driver, getElementsUtil.getLocator(locatorExpression)); LogUtil.info("显示等待页面元素出现成功, 页面元素是" + locatorExpression); }catch (Exception e){ TestSuiteByExcel.testResult = false; LogUtil.info("显示等待页面元素时出现异常,异常信息为:" + e.getMessage()); e.printStackTrace(); } } /** *定义函数press_Tab,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void press_Tab(String string1, String string2){ try{ Thread.sleep(2000); KeyBoardUtil.PressTabKey(); LogUtil.info("按Tab键成功"); } catch (Exception e) { TestSuiteByExcel.testResult = false; LogUtil.info("按Tab键出现异常,异常信息为:" + e.getMessage()); e.printStackTrace(); } } /** *定义函数pasteString,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void pasteString(String pasteContent, String string){ try{ KeyBoardUtil.setAndCtrlVClipboardData(pasteContent); LogUtil.info("成功黏贴内容:" + pasteContent); }catch (Exception e){ TestSuiteByExcel.testResult = false; LogUtil.info("黏贴内容时出现异常,具体异常信息为:" + e.getMessage()); e.printStackTrace(); } } /** *定义函数press_enter,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void press_enter(String string1, String string2){ try{ KeyBoardUtil.PressEnterKey(); LogUtil.info("按回车键成功"); }catch (Exception e){ TestSuiteByExcel.testResult = false; LogUtil.info("按回车键出现异常,具体异常信息为:" + e.getMessage()); e.printStackTrace(); } } /** *定义函数sleep,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void sleep(String sleepTime, String string){ try{ WaitElementUntil.sleep(Integer.parseInt(sleepTime)); LogUtil.info("休眠"+ Integer.parseInt(sleepTime)/1000+"秒成功"); }catch (Exception e){ TestSuiteByExcel.testResult = false; LogUtil.info("线程休眠时出现异常,具体异常信息:"+ e.getMessage()); e.printStackTrace(); } } /** *定义函数click_sendMailButton,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void click_sendMailButton(String locatorExpression, String string){ try{ /*页面上存在两个发送按钮可执行发送功能,为了使用xpath匹配方便, *同时匹配了两个发送按钮,并存储在list容器中,再随便取出一个 *按钮对象,来完成单击发送邮件按钮的操作 */ List<WebElement> buttons = driver.findElements(getElementsUtil.getLocator(locatorExpression)); buttons.get(0).click(); LogUtil.info("单击发送邮件按钮成功"); System.out.println("发送按钮被成功点击"); }catch (Exception e){ TestSuiteByExcel.testResult = false; LogUtil.info("单击发送邮件按钮出现异常,异常信息为:" + e.getMessage()); e.printStackTrace(); } } /** *定义函数Assert_String,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void Assert_String(String assertString, String string){ try{ Assert.assertTrue(driver.getPageSource().contains(assertString)); LogUtil.info("成功断言关键字“" + assertString +"”"); }catch (AssertionError e){ TestSuiteByExcel.testResult = false; LogUtil.info("断言失败,具体断言失败信息:" + e.getMessage()); System.out.println("断言失败"); } } /** *定义函数close_browser,参数String为无实际值传入的参数,仅为了通过反射机制统一的使用两个函数参数调用此函数 */ public static void close_browser(String string1, String string2){ try{ System.out.println("关闭浏览器"); LogUtil.info("关闭浏览器窗口"); driver.quit(); }catch (Exception e){ TestSuiteByExcel.testResult = false; LogUtil.info("关闭浏览器出现异常,异常信息为:" + e.getMessage()); e.printStackTrace(); } } //定义函数navigate,用于获取浏览器要访问的链接 public static void navigate(String url){ driver.get(url); info("访问地址为"+url); } //用于显示等待页面元素的出现 public static void WaitFor_Element(String xpathExpression) throws Exception { By by = getElementsUtil.getLocator(xpathExpression); try{ waitWebElementPresence(driver, by); info("显示等待页面元素出现成功, 页面元素是" + xpathExpression); }catch (Exception e){ info("显示等待页面元素时出现异常,异常信息为:" + e.getMessage()); e.printStackTrace(); } } /**这是智能等待元素加载的方法*/ public void intelligentWait(WebDriver driver,int timeOut, final By by) { try { (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { WebElement element = driver.findElement(by); return element.isDisplayed(); } }); } catch (TimeoutException e) { Assert.fail("超时L !! " + timeOut + " 秒之后还没找到元素 [" + by + "]", e); } } //通过从剪切板黏贴的方式,在文件上传框体的文件名输入框中输入要上传文件的路径和名称"uploadpathandname" public static void paste_uploadFilename(String uploadpathandname){ try{ KeyBoardUtil.setAndCtrlVClipboardData(uploadpathandname); }catch (Exception e){ e.printStackTrace(); } } //页面上不止一个相同功能并且xpath相同的元素,此种情况处理是将他们存储到List中,然后用索引的方式用其一 public static void twoWay(String ElementNameInproFile){ try { List<WebElement> elements = driver.findElements(getElementsUtil.getLocator(ElementNameInproFile)); elements.get(0).click(); System.out.println("按钮被成功点击"); }catch (Exception e){ e.printStackTrace(); } } //用于等待操作,暂停几秒,函数参数以毫秒为单位 public static void sleep(String sleepTime){ try{ WaitElementUntil.sleep(Integer.parseInt(sleepTime)); }catch (Exception e){ e.printStackTrace(); } } //断言文字内容 public static void assert_String(WebDriver driver,String assertstring){ try{ Assert.assertTrue(driver.getPageSource().contains(assertstring)); info("成功断言关键字“"+ assertstring +"”"); }catch (AssertionError e){ info("断言失败,具体失败信息为:"+ e.getMessage()); System.out.println("断言失败"); } } //断言文字不存在 public static void assert_NoString(WebDriver driver, String assertstring){ try{ Assert.assertFalse(driver.getPageSource().contains(assertstring)); info("成功断言关键字“"+ assertstring +"” + “不存在”"); }catch (AssertionError e){ info("断言失败,具体信息为:" + e.getMessage()); System.out.println("断言失败"); } } //关闭浏览器 public static void close_Browser(WebDriver driver){ try{ System.out.println("关闭浏览器"); driver.quit(); }catch (Exception e){ e.printStackTrace(); } } public static WebDriver caseBrowser(String browser) { switch (browser) { case "ie": System.setProperty("webdriver.ie.driver",Path_BrowserDrivers+"IEDriverServer.exe"); driver = new InternetExplorerDriver(); break; case "firefox": System.setProperty("webdriver.gecko.driver", Path_BrowserDrivers+"geckodriver.exe"); driver = new FirefoxDriver(); break; case "chrome": System.setProperty("webdriver.chrome.driver",Path_BrowserDrivers+"chromedriver.exe"); driver = new ChromeDriver(); break; default: try { throw new Exception("浏览器错误!"); } catch (Exception e) { e.printStackTrace(); } } return driver; } public static void openBrowser(String url, String browser, int timeOutInSeconds) { driver = open_browser(browser, "davieyang"); driver.manage().timeouts().implicitlyWait(timeOutInSeconds, TimeUnit.SECONDS); driver.get(url); } public static void selectByValue(String string, String value) { Select select = new Select(driver.findElement(By.xpath(string))); select.selectByValue(value); } public static void selectByText(String string, String text) { Select select = new Select(driver.findElement(By.xpath(string))); select.selectByVisibleText(text); } public static void selectByIndex(String string, int index) { Select select = new Select(driver.findElement(By.xpath(string))); select.selectByIndex(index); } public static void switchToFrame(By locator) { driver.switchTo().frame(driver.findElement(locator)); } public static void switchToParentFrame() { driver.switchTo().defaultContent(); } public static void dismissAlert() { Alert alert = driver.switchTo().alert(); alert.dismiss(); } public static void acceptAlert() { Alert alert = driver.switchTo().alert(); alert.accept(); } public static String getAlertText() { Alert alert = driver.switchTo().alert(); return alert.getText(); } public static void inputTextToAlert(String text) { Alert alert = driver.switchTo().alert(); alert.sendKeys(text); } public static void deleteCookie(String name) { driver.manage().deleteCookieNamed(name); } public static void deleteAllCookies() { driver.manage().deleteAllCookies(); } public static Map<String, String> getCookieByName(String name) { Cookie cookie = driver.manage().getCookieNamed(name); if (cookie != null) { Map<String, String> map = new HashMap<String, String>(); map.put("name", cookie.getName()); map.put("value", cookie.getValue()); map.put("path", cookie.getPath()); map.put("domain", cookie.getDomain()); map.put("expiry", cookie.getExpiry().toString()); return map; } return null; } public static Set<Cookie> getAllCookies() { return driver.manage().getCookies(); } public static void addCookie(String name, String value) { driver.manage().addCookie(new Cookie(name, value)); } public static void addCookie(String name, String value, String path) { driver.manage().addCookie(new Cookie(name, value, path)); } public static void closeCurrentBrowser(WebDriver driver) { driver.close(); info("关闭浏览器..."); } public static void closeAllBrowser(WebDriver driver) { driver.quit(); info("关闭浏览器..."); } public static void maxBrowser(WebDriver driver) { driver.manage().window().maximize(); info("浏览器最大化..."); } public static void setBrowserSize(int width, int height) { driver.manage().window().setSize(new Dimension(width, height)); info("设置浏览器为" + width + "高度为" + height); } /**获取当前URL*/ public static String getURL(WebDriver driver) { return driver.getCurrentUrl(); } /**获取当前浏览器页面的标题*/ public static String getTitle(WebDriver driver) { return driver.getTitle(); } public void returnToPreviousPage() { driver.navigate().back(); LogUtil.info("返回到上一个页面..."); } /**在浏览器的历史中向前到下一个页面, 如果我们在最新的页面上看, 什么也不做, 即点击浏览器下一页*/ public void forwardToNextPage() { driver.navigate().forward(); LogUtil.info("Link到下一个页面..."); } public static void refreshPage() { driver.navigate().refresh(); LogUtil.info("刷新页面"); } /**WebDriver切换到当前页面*/ public static void switchToCurrentPage() { String handle = driver.getWindowHandle(); for (String tempHandle : driver.getWindowHandles()) { if(tempHandle.equals(handle)) { driver.close(); }else { driver.switchTo().window(tempHandle); } } } public static String getElementText(By locator) { return driver.findElement(locator).getText(); } public static void clearText(By locator) { driver.findElement(locator).clear(); } public static void submitForm(By locator) { driver.findElement(locator).submit(); } public static void uploadFile(By locator, String filePath) { driver.findElement(locator).sendKeys(filePath); }}
以上就是自动化测试的封装代码,希望对你有所帮助。
上一篇: 关于java8 中的steam一些东西
下一篇: 数组中的最长山脉java实现