本文通過代碼來說明selenium的使用,同時儲存該代碼。
1、建立測試報告檔案,此處使用的是XML檔案
public class FileCreate {/** * @param args * create heml file */public void createHtml(String file_name) {File file = new File(file_name) ; System.out.println("create file method");if(!file.exists()){try {file.createNewFile() ;//file is createSystem.out.println("create file ok");@SuppressWarnings("resource")FileOutputStream out=new FileOutputStream(file,true); StringBuffer sb=new StringBuffer(); sb.append("<html>"); sb.append("<head>"); sb.append("<title>uiautomator test report</title>"); sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"); sb.append("<style type=\"text/css\">"); sb.append("TABLE{border-collapse:collapse;border-left:solid 1 #000000; border-top:solid 1 #000000;padding:5px;}<br>"); sb.append("TH{border-right:solid 1 #000000;border-bottom:solid 1 #000000;}"); sb.append("TD{font:normal;border-right:solid 1 #000000;border-bottom:solid 1 #000000;}"); sb.append("</style>"); sb.append("<script language=\"javascript\" type=\"text/javascript\">");sb.append("function click_a(divDisplay)");sb.append("{if(document.getElementById(divDisplay).style.display != \"block\")") ;sb.append("{document.getElementById(divDisplay).style.display = \"block\";}"); sb.append("else{document.getElementById(divDisplay).style.display = \"none\";}}");sb.append("function click_b(name){");sb.append("var trs=document.getElementsByName(name);");sb.append("var o=null;");sb.append("for(var i=0,len=trs.length;i<len;i++){");sb.append("o=trs[i];");sb.append("if(o.style.display != \"block\")");sb.append("{o.style.display=\"block\";}");sb.append("else{o.style.display=\"none\";");sb.append("}}}");sb.append("</script>");sb.append("</head><br>"); sb.append("<body bgcolor=\"#FFF8DC\">"); sb.append("<div align=\"center\">"); sb.append("<br>"); sb.append("<br>");sb.append("hello");sb.append("<form id=\"form1\" runat=\"server\"> ");sb.append("<div><a onclick=\"return click_a(\'divOne_1\')\" style=\"cursor:pointer;\">open</a> ");sb.append("<div id=\"divOne_1\" style=\"display:none;\">div_one display</div> ");out.write(sb.toString().getBytes("utf-8"));System.out.println("Step pppp ") ;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}
2、通過在測試報告中添加相關的log,來顯示測試步驟、測試結果。
public class FileLog { /** * * @param file_name: 需要添加log的檔案,此處使用HTML檔案 * @param title:設施標題 * @param flag * @throws IOException */ public void addLogTitle(String file_name,String title,Boolean flag) throws IOException{File file = new File(file_name) ;@SuppressWarnings("resource")FileOutputStream out=new FileOutputStream(file,true); StringBuffer sb=new StringBuffer(); if(flag == true){ sb.append("<div><a onclick=\"return click_b(\'"+ title + "\')\" style=\"cursor:pointer;color:#FF0000\">"+ title + "</a> "); }else { sb.append("<div><a onclick=\"return click_b(\'"+ title + "\')\" style=\"cursor:pointer;color:#008000\">"+ title + "</a> "); }out.write(sb.toString().getBytes("utf-8"));} public static void replaceTxtByStr(String file_name,String oldStr,String replaceStr) { String temp = ""; try { File file = new File(file_name); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); StringBuffer buf = new StringBuffer(); // 儲存該行前面的內容 for (int j = 1; (temp = br.readLine()) != null && !temp.equals(oldStr); j++) { buf = buf.append(temp); buf = buf.append(System.getProperty("line.separator")); } // 將內容插入 buf = buf.append(replaceStr); // 儲存該行後面的內容 while ((temp = br.readLine()) != null) { buf = buf.append(System.getProperty("line.separator")); buf = buf.append(temp); } br.close(); FileOutputStream fos = new FileOutputStream(file); PrintWriter pw = new PrintWriter(fos); pw.write(buf.toString().toCharArray()); pw.flush(); pw.close(); } catch (IOException e) { e.printStackTrace(); } } public void addLogTitle11(String file_name,String title) throws IOException{File file = new File(file_name) ;@SuppressWarnings("resource")FileOutputStream out=new FileOutputStream(file,true); String sb = title ; out.write(sb.toString().getBytes("utf-8"));} public void addLogStep(String file_name,String title, String flag, String log) throws IOException{File file = new File(file_name) ;@SuppressWarnings("resource")FileOutputStream out=new FileOutputStream(file,true); StringBuffer sb=new StringBuffer(); String time = GetTime() ; //sb.append("<div><a onclick=\"return click_a(\'"+ title + "\')\" style=\"cursor:pointer;color:#FF0000\">"+ title + "</a> "); //add log sb.append("<div name=\"" + title + "\" style=\"display:none;color:#008000\">"+ log +"</div> "); sb.append("<br/>") ; //add image if(flag != null){ sb.append("<img name=\"" + title + "\" style=\"display:none;\" src=\" "+ "images" + "\\" + flag + ".png" + "\"> "); } out.write(sb.toString().getBytes("utf-8"));} public String GetTime(){ long time=System.currentTimeMillis(); //long now = android.os.SystemClock.uptimeMillis(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date_new = new Date(time); String time_new = format.format(date_new); return time_new ; } }
3、精簡後的添加測試結果log的代碼
public class FileLogNew {public static void main(String[] args) throws IOException {// TODO Auto-generated method stub//StringBuffer sb = new StringBuffer();//String filename = "./test.html" ;//addLogTitle(sb, "test 002") ;//addLogStep(sb, "", "test 002", "step 1") ;//replaceText(sb,"FF0000","008000") ;//addLog(filename, sb) ;//System.out.println("test is finished. "); }/** * * @param sb:StringBuffer 臨時變數 * @param title:測試例標題,且作為該條測試例的控制標籤 * @return:返回StringBuffer 臨時變數 * @throws IOException */public StringBuffer addLogTitle(StringBuffer sb, String title) throws IOException {sb.append("<div><a onclick=\"return click_b(\'" + title+ "\')\" style=\"cursor:pointer;color:#FF0000\">" + title+ "</a>");System.out.println("add title");return sb;}/** * * @param sb:StringBuffer 臨時變數 * @param imageName:如果該變數有值,則代表該步驟包括截圖,否則設定為”“即可 * @param title:測試例標題,且作為該條測試例的控制標籤 * @param log:添加的測試步驟 * @return:StringBuffer 臨時變數 * @throws IOException */public StringBuffer addLogStep(StringBuffer sb, String imageName, String title, String log) throws IOException { //add log sb.append("<div name=\"" + title + "\" style=\"display:none;color:#008000\">"+ log +"</div>"); //add image if(imageName != ""){ sb.append("<img name=\"" + title + "\" style=\"display:none;\" src=\" "+ "images" + "\\" + imageName + ".png" + "\">"); }return sb;}/** * * @param sb:StringBuffer 臨時變數 * @param older:替換的舊文本 * @param newer:替換的新文本 * @return:StringBuffer 臨時變數 * @throws IOException */public StringBuffer replaceText(StringBuffer sb, String older, String newer) throws IOException {int index= sb.lastIndexOf(older);sb.replace(index, index+7, newer);return sb;}/** * 倒序尋找字串FF0000,然後替換為008000 * @param sb:StringBuffer 臨時變數 * @return:StringBuffer 臨時變數 * @throws IOException */public StringBuffer changeLastRedToGreen(StringBuffer sb) throws IOException {int index= sb.lastIndexOf("FF0000");sb.replace(index, index+6, "008000");return sb;}/** * 倒序尋找字串008000,然後替換為FF0000 * @param sb:StringBuffer 臨時變數 * @return:StringBuffer 臨時變數 * @throws IOException */public StringBuffer changeLastGreenToRed(StringBuffer sb) throws IOException {int index= sb.lastIndexOf("008000");sb.replace(index, index+6, "FF0000");return sb;}/** * 建立檔案,然後添加StringBuffer 臨時變數到該檔案 * @param file_name:建立的檔案名稱字,如果不存在則進行建立 * @param buffer:StringBuffer 臨時變數 * @throws IOException */public void addLog(String file_name, StringBuffer buffer) throws IOException {File file = new File(file_name);@SuppressWarnings("resource")FileOutputStream out = new FileOutputStream(file, true);String sb = buffer.toString();out.write(sb.getBytes("utf-8"));}/** * * @return:擷取的系統時間 */ public String GetTime(){ long time=System.currentTimeMillis(); //long now = android.os.SystemClock.uptimeMillis(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date_new = new Date(time); String time_new = format.format(date_new); return time_new ; } }
4、建立測試檔案夾
public class FolderCreate {/** * 建立檔案夾 * @param folder */public void createFolder(String folder){System.out.println("create folder method");File dirFirstFolder = new File(folder);if(!dirFirstFolder.exists()) {System.out.println("create folder OK "); dirFirstFolder.mkdirs(); System.out.println("create folder ok"); } }}
5、common方法
public class Common {/** * 截圖功能 * @param webDriver * @param directory:截圖路徑 * @param captureName:截圖名字 * @param format:截圖的格式 */public static void captureScreen(WebDriver webDriver, String directory,String captureName, String format){File screenShotFile = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE ); try { FileUtils.copyFile (screenShotFile, new File(directory + "/" + captureName + "." + format)); } catch (IOException e) { e.printStackTrace(); } }/** * 判斷尋找的控制項是否存在 * @param webDriver * @param Locator:尋找控制項的方式 * @return */public static boolean ElementExist(WebDriver webDriver, By Locator) {try {webDriver.findElement(Locator);return true;} catch (org.openqa.selenium.NoSuchElementException ex) {return false;}}}
6、具體代碼實現
public class QA {public static String folder = "./TestData"; // 此處為測試建立的檔案夾,用來存放測試資料public static String folderImage = "./TestData/images";private static String file = "Result.html"; // 此處為測試建立的HTML檔案private static String flag = "";privatestatic FolderCreate folderC = new FolderCreate() ;privatestatic FileCreate fileC = new FileCreate() ;privatestatic FileLogNew fileL = new FileLogNew() ;privatestatic WebDriver firfox = new FirefoxDriver();public static void main(String[] args) throws Exception {folderC.createFolder(folder);folderC.createFolder(folderImage);fileC.createHtml(folder + "/" + file);first();// second() ;}public static void first() throws InterruptedException, IOException {String title = "first" + "_" + fileL.GetTime() ;StringBuffer sb = new StringBuffer(); String imageName = "" ; System.out.println("Step 1: Open " + "web_name" + " app") ;fileL.addLogTitle(sb, title) ;firfox.get("http://www.baidu.com");Thread.sleep(2000);imageName = "step 1" ;fileL.addLogStep(sb, imageName, title, "Step 1: web is opened. ") ;WebElement input = firfox.findElement(By.name("wd"));input.sendKeys("abc");Thread.sleep(2000);imageName = "step 2" ;fileL.addLogStep(sb, imageName, title, "Step 2: input keyword. ") ;WebElement submit = firfox.findElement(By.id("su"));if(submit.isDisplayed()){submit.click();Thread.sleep(2000);}imageName = "step 3" ;fileL.addLogStep(sb, imageName, title, "Step 3: click submit button. ") ;if(Common.ElementExist(firfox, By.className("t555555555"))){imageName = "step 4" ;fileL.addLogStep(sb, imageName, title, "Step 4: new page is opened ") ;fileL.changeLastRedToGreen(sb) ;fileL.addLog(folder + "/" + file, sb);Common.captureScreen(firfox, folderImage, imageName, "png") ;System.out.println("Step 4: new page is opened ") ;}else{imageName = "step 4" ;fileL.addLogStep(sb, imageName, title, "Step 4: new page is not opened ");fileL.changeLastGreenToRed(sb) ;fileL.addLog(folder + "/" + file, sb);Common.captureScreen(firfox, folderImage, imageName, "png") ;System.out.println("Step 4: new page is not opened ") ;}//abc.click();// firfox.close();}public static void second() throws InterruptedException {File file = new File("src/html_file/ding_wei.html");String filePath = "file:///" + file.getAbsolutePath();System.out.printf("now accesss %s \n", filePath);firfox.get(filePath);Thread.sleep(2000);// by idWebElement mail = firfox.findElement(By.id("inputEmail"));mail.click();Thread.sleep(2000);mail.sendKeys("email name");Thread.sleep(2000);// by nameWebElement pwd = firfox.findElement(By.name("password"));pwd.sendKeys("passwod");Thread.sleep(2000);// by tagnameString classOfForm = firfox.findElement(By.tagName("form")).getAttribute("class");System.out.printf("%s\n", classOfForm);Thread.sleep(2000);// by link textWebElement link = firfox.findElement(By.linkText("register"));((JavascriptExecutor) firfox).executeScript("$(arguments[0]).fadeOut().fadeIn()", link);Thread.sleep(2000);link.click();Thread.sleep(2000);// by link calssWebElement submit = firfox.findElement(By.className("btn"));submit.click();}}