首页 / JAVA / Java自动化测试常用的工具代码
Java自动化测试常用的工具代码
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java自动化测试常用的工具代码,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含20604字,纯文字阅读大概需要30分钟。
内容图文
![Java自动化测试常用的工具代码](/upload/InfoBanner/zyjiaocheng/656/9a3629ae1fd24c12a0c9c50cf17033df.jpg)
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;
public class snap {
private String fileName;
private String defaultName="GuiCamera";
static int serialNum=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;
}
/**
* 对屏幕进行拍照
*
* **/
public void 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:按照指定的高度 宽度进行截屏
public class snapWithSize {
public void snap(int height,int width,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;
public class snapFree {
private String fileName;
private String defaultName="GuiCamera";
static int serialNum=0;
private String imageFormat;//图像文件的格式
private String defaultImageFormat="jpg";
public snapFree(){
fileName=defaultName;
imageFormat=defaultImageFormat;
}
public snapFree(String s,String format) {
fileName=s;
imageFormat=format;
}
/**
* 对屏幕进行拍照
*
* **/
public void snapshot(int x,int y,int width,int Height){
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);
}
}
public static void 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;
public class wirteContext {
private String contxt = "写入内容";
private String path = "C:\\output.txt";
@Test
public void wirteContext() {
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;
public class TestLogin {
@Test
public void 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;
public class ReadCSV {
public static void main(String args[])
{
ArrayList<String []> list = readCsv("C:\\Users\\Administrator\\Desktop\\test.csv");
for(int i=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("-------------------");
}
}
public static 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(int i=0;i<list.size();i++)
{
data[i]=list.get(i);
}
return list;
}
}
输出:
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.*;
public class ReadExcel{
public static void 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;
public class WriteExcel {
private static ArrayList<String> arrayList;
public static void main(String[] args) {
arrayList = new ArrayList<String>();
arrayList.add("Streamax1");
arrayList.add("Streamax2");
arrayList.add("Streamax3");
WriteExcel.createExcel("c:/test.xls","第一层", 0);
}
public static void createExcel(String path,String sheetNmae,int sheetNumber) {
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(int i = 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;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
public class RegisterNew {
private static WebDriver driver = new FirefoxDriver();
// RegisterBean有有参构造函数
private RegisterBean rs = new RegisterBean(driver);
@Test
public void registrnew() {
driver.get("http://xx.xx.128.xx:xx端口");
rs.login("123", "qwe");
//断言
assertEquals(true, true);
}
@AfterMethod
public void 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;
public class RW {
private RW rw = new RW();
/**
*
*/
@Test
public void Test1() {
//将照片复制1000张到D:/123这个文件夹下
for (int i = 0; i < 1000; i++) {
rw.copyFile("c:/1.JPG", "D:/123/"+i+".JPG");
}
}
@Test
public void Test2() {
rw.copyFolder("D:/123", "C:/1234");
}
/***
* 复制单个文件*
*
* @param oldPath
* String 原文件路径 如:c:/fqf.txt*
* @param newPath
* String 复制后路径 如:f:/fqf.txt*@return boolean
*/
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldPath); // 读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
/**
* 复制整个文件夹内容
*
* @param oldPath
* String 原文件路径 如:c:/fqf
* @param newPath
* String 复制后路径 如:f:/fqf/ff
* @return boolean
*/
public void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath + "/" + (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
} catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
}
11:文件的复制粘贴(本地文件夹到ftp路径)
commons-net-3.6.jar包
package Test1;
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.testng.annotations.Test;
public class ftpUpload {
@Test
public void testFtpClient(){
//创建一个FTPClient对象
FTPClient ftpClient = new FTPClient();
//创建FTP连接,端口号可以设定,我的是22,默认是21
try {
ftpClient.connect("xxx.xxx.151.47",21);
//登录FTP服务器,使用用户名和密码 下列写法是没有密码的写法
ftpClient.login("anonymous", "");
//ftpClient.enterRemotePassiveMode();
//ftpClient.setControlEncoding("gb18030");
//上传文件,读取本地文件
String path = "C:/1.jpg";
FileInputStream inputStream = new FileInputStream(new File(path));
//设置上传的路径
String pathname = "/abc";//这个路径就是FTP服务端存储的路径,先要确保abc这个文件目录存在
ftpClient.changeWorkingDirectory(pathname); //保证上传到指定的目录下 如果没有这一句 将会上传到ftp根目录下
//参数一:服务器端文档名;参数二:上传文档的inputStream
String remote = "1.jpg";
ftpClient.storeFile(remote, inputStream);
//关闭连接
ftpClient.logout();
} catch (Exception e) {
e.printStackTrace();
}
}
}
12:读取一个文件夹下所有文件的文件名称全称(包括后缀名)
package streamax.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ReadFileNanes {
//文件名列表
private static List<String> fileList = new ArrayList<String>();
/**
* @param args
*/
public static void main(String[] args) {
//该目录下有123.jpg 和 20180515153634_10.jpg两文件
printAllFileNames("C:/Users/Administrator/Desktop/Test1");
}
public static void printAllFileNames(String path) {
if (null != path) {
File file = new File(path);
if (file.exists()) {
File[] list = file.listFiles();
if(null != list){
for (File child : list) {
if (child.isFile()) {
fileList.add(child.getAbsolutePath());
String filePath = child.getAbsolutePath();
String jieguo = filePath.substring(filePath.indexOf("Test1")+6,filePath.indexOf(".jpg")+4);
System.out.println(jieguo);
//输出内容为
// 123.jpg
// 20180515153634_10.jpg
// System.out.println("==============");
} else if (child.isDirectory()) {
printAllFileNames(child.getAbsolutePath());
}
}
}
}
}
}
}
13:截屏---按照指定的坐标截取指定尺寸大小的图片
package CommUtils;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class snapFree {
// ===源图片路径名称如:c:\1.jpg
private String srcpath;
// ===剪切图片存放路径名称.如:c:\2.jpg
private String subpath;
// ===剪切点x坐标
private int x;
private int y;
// ===剪切点宽度
private int width;
private int height;
public snapFree() {
}
public snapFree(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* 对图片裁剪,并把裁剪完蛋新图片保存 。
*/
public void cut() throws IOException {
FileInputStream is = null;
ImageInputStream iis = null;
try {
// 读取图片文件
is = new FileInputStream(srcpath);
/*
* 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。
* 参数:formatName - 包含非正式格式名称 . (例如 "jpeg" 或 "tiff")等 。
*/
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = it.next();
// 获取图片流
iis = ImageIO.createImageInputStream(is);
/*
* <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。
* 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
*/
reader.setInput(iis, true);
/*
* <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O
* 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其 ImageReader 实现的
* getDefaultReadParam 方法中返回 ImageReadParam 的实例。
*/
ImageReadParam param = reader.getDefaultReadParam();
/*
* 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象
* 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。
*/
Rectangle rect = new Rectangle(x, y, width, height);
// 提供一个 BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
/*
* 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的
* BufferedImage 返回。
*/
BufferedImage bi = reader.read(0, param);
// 保存新图片
ImageIO.write(bi, "jpg", new File(subpath));
} finally {
if (is != null)
is.close();
if (iis != null)
iis.close();
}
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getSrcpath() {
return srcpath;
}
public void setSrcpath(String srcpath) {
this.srcpath = srcpath;
}
public String getSubpath() {
return subpath;
}
public void setSubpath(String subpath) {
this.subpath = subpath;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public static void main(String[] args) {
snapFree operateImage = new snapFree(469, 222, 100, 100);//开始的宽度,开始的高度,截图宽度,截图高度
operateImage.srcpath = "C:/Users/Administrator/Desktop/1.jpg";
operateImage.subpath = "C:/Users/Administrator/Desktop/2.jpg";
try {
operateImage.cut();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.14 确定/取消对话框执行对应操作
package enter.entrys;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.junit.Test;
public class demo {
@Test
public void test(){
int n = JOptionPane.showConfirmDialog(null, "确认删除吗?", "确认对话框", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
// JOptionPane.showMessageDialog(new JFrame(),"已删除");
System.out.println("执行确定的操作");
} else if (n == JOptionPane.NO_OPTION) {
// JOptionPane.showMessageDialog(new JFrame(),"已取消");
System.out.println("执行取消的操作");
}
}
}
内容总结
以上是互联网集市为您收集整理的Java自动化测试常用的工具代码全部内容,希望文章能够帮你解决Java自动化测试常用的工具代码所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。