本文通过代码来说明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 create
System.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 οnclick=\"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 block
e.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 οnclick=\"return click_b(\'"+ title + "\')\" style=\"cursor:pointer;color:#FF0000\">"+ title + "</a> ");
}else {
sb.append("<div><a οnclick=\"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 οnclick=\"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 οnclick=\"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 = "";
private static FolderCreate folderC = new FolderCreate() ;
private static FileCreate fileC = new FileCreate() ;
private static FileLogNew fileL = new FileLogNew() ;
private static 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 id
WebElement mail = firfox.findElement(By.id("inputEmail"));
mail.click();
Thread.sleep(2000);
mail.sendKeys("email name");
Thread.sleep(2000);
// by name
WebElement pwd = firfox.findElement(By.name("password"));
pwd.sendKeys("passwod");
Thread.sleep(2000);
// by tagname
String classOfForm = firfox.findElement(By.tagName("form"))
.getAttribute("class");
System.out.printf("%s\n", classOfForm);
Thread.sleep(2000);
// by link text
WebElement link = firfox.findElement(By.linkText("register"));
((JavascriptExecutor) firfox).executeScript(
"$(arguments[0]).fadeOut().fadeIn()", link);
Thread.sleep(2000);
link.click();
Thread.sleep(2000);
// by link calss
WebElement submit = firfox.findElement(By.className("btn"));
submit.click();
}
}