1. 程式人生 > >Java自動化測試常用的工具程式碼

Java自動化測試常用的工具程式碼

1:簡單的截圖——截全屏

package com.auto.Test;

import java.awt.Dimension;

import java.awt.Rectangle;

import java.awt.Robot;

import java.awt.Toolkit;

import java.awt.image.BufferedImage;

import java.io.File;

import javax.imageio.ImageIO;

publicclass snap {

private

 String fileName;

private String defaultName="GuiCamera";

staticintserialNum=0;

private String imageFormat;//影象檔案的格式

private String defaultImageFormat="jpg";

Dimension d=Toolkit.getDefaultToolkit().getScreenSize();

public  snap(){

fileName=defaultName;

imageFormat=defaultImageFormat

;

}

public snap(String s,String format) {

fileName=s;

imageFormat=format;

}

/**

 * 對螢幕進行拍照

 *

 * **/

publicvoid snapshot(){

try {

//拷貝螢幕到一個BufferedImage物件screenshot

BufferedImage screenshot=(new Robot()).createScreenCapture(

new Rectangle(0,0,(

int)d.getWidth(),(int)d.getHeight()));

serialNum++;

//根據檔案字首變數和檔案格式變數,自動生成檔名

String name=fileName+String.valueOf(serialNum)+"."+imageFormat;

System.out.println(name);

File f=new File(name);

System.out.println("Save File-"+name);

//將screenshot物件寫入影象檔案

ImageIO.write(screenshot, imageFormat, f);

System.out.println("..Finished");

} catch (Exception e) {

System.out.println(e);

}

}

/*

public static void main(String[] args) {

//"C:\\sally\\bootstrap柵格"是根據自己隨意找的一個圖片形式,"png"是圖片的格式

snap cam=new snap("C:\\sally\\bootstrap柵格","png");

cam.snapshot();

}

*/

}

2:按照指定的高度 寬度進行截圖

publicclass snapWithSize {

publicvoid snap(intheight,intwidth,String filename) {

try {

    Robot robot=new Robot();

//根據指定的區域抓取螢幕的指定區域,1300是長度,800是寬度。

    BufferedImage bi=robot.createScreenCapture(new Rectangle(height,width));

//把抓取到的內容寫到一個jpg檔案中

    ImageIO.write(bi, "jpg", new File(filename+".png"));

} catch (AWTException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

3:截圖---按照指定的座標開始截圖指定高度 寬度的圖片

package CommUtils;  

import java.awt.Rectangle;  

import java.awt.Robot;   

import java.awt.image.BufferedImage;  

import java.io.File;  

import javax.imageio.ImageIO;  

publicclass snapFree {  

private String fileName;  

private String defaultName="GuiCamera";  

staticintserialNum=0;  

private String imageFormat;//影象檔案的格式  

private String defaultImageFormat="jpg";   

public  snapFree(){  

fileName=defaultName;  

imageFormat=defaultImageFormat;  

    }  

public snapFree(String s,String format) {  

fileName=s;  

imageFormat=format;  

    }  

/**

     * 對螢幕進行拍照

     *  

     * **/

publicvoid snapshot(intx,inty,intwidth,intHeight){  

try {  

//拷貝螢幕到一個BufferedImage物件screenshot  

            BufferedImage screenshot=(new Robot()).createScreenCapture(  

new Rectangle(x,y,width,Height));  

serialNum++;  

//根據檔案字首變數和檔案格式變數,自動生成檔名  

            String name=fileName+String.valueOf(serialNum)+"."+imageFormat;  

            System.out.println(name);  

            File f=new File(name);  

            System.out.println("Save File-"+name);  

//將screenshot物件寫入影象檔案  

            ImageIO.write(screenshot, imageFormat, f);  

            System.out.println("..Finished");  

        } catch (Exception e) {  

            System.out.println(e);  

        }  

    }  

publicstaticvoid main(String[] args) {

//"C:\\sally\\bootstrap柵格"是根據自己隨意找的一個圖片形式,"png"是圖片的格式  

        snapFree cam=new snapFree("C:\\bootstrap柵格","jpg");  

cam.snapshot(200,200,300,400);  

    }  

}

4:寫入資料到txt檔案

主程式

package com.auto.Test12306;

import org.junit.Test;

publicclass wirteContext {

private String contxt = "寫入內容";

private String path = "C:\\output.txt";

@Test

publicvoidwirteContext() {

TestLogin testLogin = new TestLogin();

//傳入 書寫內容和路徑

testLogin.outPut(contxt,path);

}

}

寫入流

package com.auto.Test12306;

import java.io.File;

import java.io.BufferedWriter;

import java.io.FileWriter;

import org.junit.Test;

publicclass TestLogin {

@Test

publicvoid outPut(String wirteContext,String path) {

try {

/* 寫入Txt檔案 */

File writename = new File(path); // 相對路徑,如果沒有則要建立一個新的output。txt檔案

writename.createNewFile(); // 建立新檔案

BufferedWriter out = new BufferedWriter(new FileWriter(writename));

out.write(wirteContext);

out.flush(); // 把快取區內容壓入檔案

out.close(); // 最後記得關閉檔案

} catch (Exception e) {

e.printStackTrace();

}

}

}

5:讀取CSV檔案

需要javacsv.jar包

package com.auto.lyzb.utils;

import java.nio.charset.Charset;

import java.util.ArrayList;

import com.csvreader.CsvReader;

publicclass ReadCSV {

publicstaticvoid main(String args[])

    {

        ArrayList<String []> list = readCsv("C:\\Users\\Administrator\\Desktop\\test.csv");

for(inti=0;i<list.size();i++)

        {

            System.out.println(list.get(i)[0]);//name

            System.out.println(list.get(i)[1]);//age

            System.out.println(list.get(i)[2]);//sex

            System.out.println("-------------------");

        }

}

publicstatic ArrayList<String []> readCsv(String filePath)

    {

        ArrayList<String[]> list = new ArrayList<String []>();//建立儲存資料集合

//建立csvreader讀取

        CsvReader cReader = null;

try {

cReader = new CsvReader(filePath,',',Charset.forName("GBK"));

//是否跳過表頭

cReader.readHeaders();

//錄入資料

while(cReader.readRecord()){

list.add(cReader.getValues());

            }

        } catch (Exception e) {

e.printStackTrace();

        }finally{

cReader.close();

        }

//如果使用testng的DataProvider,可以返回一個二維陣列

        Object data[][] = new Object[list.size()][];

for(inti=0;i<list.size();i++)

        {

data[i]=list.get(i);

        }        

returnlist;

    }

}

輸出:

QQ1

12

-------------------

QQ2

13

-------------------

QQ3

14

-------------------

QQ4

15

-------------------

QQ5

16

-------------------

QQ6

17

6:讀取excel檔案內容

Maven匯入jxl.jar包

<dependency>

    <groupId>com.hynnet</groupId>

    <artifactId>jxl</artifactId>

    <version>2.6.12.1</version>

</dependency>

package Auto.StreamaxTest.Case;  

import java.io.File;  

import jxl.*;   

publicclass ReadExcel{  

publicstaticvoid main(String[] args) {  

        Sheet sheet = null;  

        Workbook book = null;  

        Cell cell1 = null;  

try {   

//hello.xls為要讀取的excel檔名  

book= Workbook.getWorkbook(new File("C:/Users/Administrator/Desktop/Auto_CSV File/AddCarGroup.xls"));   

//獲得第一個工作表物件(ecxel中sheet的編號從0開始,0,1,2,3,....)  

sheet=book.getSheet(0);   

//獲取左上角的單元格  

cell1=sheet.getCell(1,1);  

            System.out.println(cell1.getContents());   

        }  

catch(Exception e)  { }   

    }  

7:像指定行列的excel表格中寫入指定資料

package CommUtils;

import java.io.File;

import java.util.ArrayList;

import jxl.Workbook;

import jxl.write.Label;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

publicclass WriteExcel {

privatestatic ArrayList<String> arrayList;

publicstaticvoid main(String[] args) {

arrayList = new ArrayList<String>();

arrayList.add("Streamax1");

arrayList.add("Streamax2");

arrayList.add("Streamax3");

WriteExcel.createExcel("c:/test.xls","第一層", 0);

}

publicstaticvoid createExcel(String path,String sheetNmae,intsheetNumber) {

try {

// 在path路徑下建立一個excel檔案

WritableWorkbook wbook = Workbook.createWorkbook(new File(path));

// 建立一個工作表 第一個工作區

WritableSheet wsheet = wbook.createSheet(sheetNmae, sheetNumber);

//WritableSheet wsheet1 = wbook.createSheet("資料清單2", 1);

//WritableSheet wsheet2 = wbook.createSheet("資料清單3", 2);

/**

// 設定excel裡的字型

WritableFont wf = new WritableFont(WritableFont.ARIAL, 12, WritableFont.NO_BOLD, false);

// 給標題規定字型的格式

WritableCellFormat titleFormat = new WritableCellFormat(wf);

String[] title = { "賬號", "密碼" };

// 設定表頭

for (int i = 0; i < title.length; i++) {

// 一列列的打印表頭 按照我們規定的格式

Label excelTitle = new Label(i, 0, title[i], titleFormat);

// 把標頭加到我們的工作區

wsheet.addCell(excelTitle);

}

*/

for(inti = 0;i<arrayList.size(); i++){

//向第i列 第二行寫入內容

Label lable = new Label(i, 1, arrayList.get(i));

// 把值加到工作表中

wsheet.addCell(lable);

}

// 寫入檔案

wbook.write();

wbook.close();

System.out.println("建立成功!");

} catch (Exception e) {

// TODO: handle exception

}

}

}

8:寫入內容到CSV檔案

需要javacsv.jar包

package streamax.test;    

import java.io.BufferedWriter;    

import java.io.File;    

import java.io.FileNotFoundException;    

import java.io.FileWriter;    

import java.io.IOException;    

public class WriteCSV {    

  public static void Wirtecsv(String filePath,String WirteContext) {    

    try {    

      File csv = new File(filePath); // CSV資料檔案  例如:C:/Users/Administrator/Desktop/Test1/Test.csv

      BufferedWriter bw = new BufferedWriter(new FileWriter(csv, true)); // 附加   

      // 新增新的資料行   

      bw.write(WirteContext);    

      bw.newLine();    

      bw.close();    

    } catch (FileNotFoundException e) {    

      // File物件的建立過程中的異常捕獲   

      e.printStackTrace();    

    } catch (IOException e) {    

      // BufferedWriter在關閉物件捕捉異常   

      e.printStackTrace();    

    }    

  }    

}  

9:動態WebElement
Utils函式 定位元素

package com.auto.lyzb.user;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.FindBy;

public class RegisterBean {

private WebDriver driver;

@FindBy(linkText = "使用者名稱")

private WebElement ele1;

@FindBy(linkText = "密碼")

private WebElement ele2;

@FindBy(linkText = "登入")

private WebElement ele3;

//建構函式  建立物件時傳入driver

public RegisterBean(WebDriver driver) {

super();

this.driver = driver;

}

public void login(String username,String password) {

ele1.sendKeys(username);

ele2.sendKeys(password);

ele3.click();

}

}

主測試函式 用來執行登入動作

package com.auto.lyzb.user;

importstatic org.testng.Assert.assertEquals;

importstaticorg.testng.Assert.assertTrue;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.Test;

publicclass RegisterNew {

privatestatic WebDriver driver = new FirefoxDriver();

// RegisterBean有有參建構函式

private RegisterBean rs = new RegisterBean(driver);

@Test

publicvoid registrnew() {

driver.get("http://xx.xx.128.xx:xx埠");

rs.login("123", "qwe");

//斷言

assertEquals(true, true);

}

@AfterMethod

publicvoid closedIE() {

driver.quit();

}

}

10:檔案/資料夾的複製貼上(本地資料夾到資料夾)

package Utils;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import org.junit.Test;

publicclass RW {

private RW rw = new RW();

/**

 *

 */

@Test

publicvoid Test1() {

//將照片複製1000張到D:/123這個資料夾下

for (inti = 0; i < 1000; i++) {

rw.copyFile("c:/1.JPG", "D:/123/"+i+".JPG");

}

}

@Test

publicvoid Test2() {

rw.copyFolder("D:/123", "C:/1234");

}

/***

 * 複製單個檔案*

 *

 * @param oldPath

 *            String 原檔案路徑 如:c:/fqf.txt*

 * @param newPath

 *            String 複製後路徑 如:f:/fqf.txt*@return boolean

 */

publicvoid copyFile(String oldPath, String newPath) {

try {

intbytesum = 0;

intbyteread = 0;

File oldfile = new File(oldPath);

if (oldfile.exists()) { // 檔案存在時

InputStream inStream = new FileInputStream(oldPath); // 讀入原檔案

FileOutputStream fs = new FileOutputStream(newPath);

byte[] buffer = newbyte[1444];

intlength;

while ((byteread =

相關推薦

no