java 自动化测试小功能集锦

1.  java 调用执行shell 命令

package com.mkyong.shell;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellComand {
	public static void main(String[] args) {
		ExecuteShellComand obj = new ExecuteShellComand();
		String domainName = "google.com";
		//in mac oxs
		String command = "ping -c 3 " + domainName;

		//in windows
		//String command = "ping -n 3 " + domainName;
		String output = obj.executeCommand(command);
		System.out.println(output);
	}

	private String executeCommand(String command) {
		StringBuffer output = new StringBuffer();
		Process p;
		try {
			p = Runtime.getRuntime().exec(command);
			p.waitFor();
			BufferedReader reader = 
                            new BufferedReader(new InputStreamReader(p.getInputStream()));
                        String line = "";			
			while ((line = reader.readLine())!= null) {
				output.append(line + "\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return output.toString();
	}
}

转自:http://www.mkyong.com/java/how-to-execute-shell-command-from-java/


2. java 按时间创建执行日志目录

public static String mkReportDir(){
// 创建报告存放目录,以日期为标记
String reportRootDir="/root/log/";         // windows平台 D:\\reports

String timeDir = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());

String reportDir = reportRootDir + timeDir;           // linux平台

// String reportDir = reportRootDir + "\\\\" + timeDir;             // windows 平台

File file = new File(reportDir);
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();
}
if(!file.exists() && !file.isDirectory()){
file.mkdir();
}

System.out.println(file.getAbsolutePath());
return file.getAbsolutePath();
}


3. java 将log写入文件

  FileWriter fileWriter = new FileWriter(reportDir+"/1.log", true);
BufferedWriter bWriter = new BufferedWriter(fileWriter);
bWriter.write("123");
bWriter.newLine();
bWriter.flush();
bWriter.close();

4.  java连接mysql数据库

String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://12345678xxx.sh.cdb.myqcloud.com:3306/xxxdb";
String user = "xxxuser";
String password = "xxxpassword";
int result = 0;
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
if(!conn.isClosed()){

}else{
System.out.println("数据库连接失败");
}
Statement statement = conn.createStatement();

ResultSet rs = statement.executeQuery(sql);

while(rs.next()){
result = rs.getInt("dbResult");  // 如 String sql = "select count(*)  dbResult from orders  where userid = 888";
}
/* while(rs.next()){
dbResult = rs.getString(dbResult);
System.out.println(dbResult);
}*/

rs.close();
System.out.println("connection closed...");
conn.close();

return result;
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("没有返回");
return 0;
}

5. 创建并写入excel表

String logDir = "c:\\log\\wxq\\";
String fileName = logDir + new SimpleDateFormat("yyyy_MM_dd").format(new Date()) + ".xls";
File file = new File(fileName);
WritableWorkbook book;
if (file.exists()) {
file.delete();
Thread.sleep(100);
}
book = Workbook.createWorkbook(file);
WritableSheet sheet = book.createSheet("群聊人数统计", 0);
Label xiaoqu_title = new Label(0, 0, "小区名");
Label renshu_title = new Label(1, 0, "人数");
sheet.addCell(xiaoqu_title);
sheet.addCell(renshu_title);
book.write();
book.close();


6.  java 调用执行js 并返回结果:

JavascriptExecutor js = (JavascriptExecutor) wd; // WebDriver
title_count = (String) js.executeScript("return document.getElementsByClassName(\"title_count ng-binding ng-scope\")[0].innerText;");


7.  map有序化,按key值:

Demo.java 文件

package com.yang.selenium;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Demo {
public static void main(String[] args) {

HashMap map = new HashMap();
map.put("重庆一号", "2");
map.put("重庆二号", "2");
map.put("重庆三号", "2");
map.put("重庆四号", "2");
map.put("重庆五号", "2");

map.put("合肥一号", "3");
map.put("合肥二号", "3");
map.put("合肥三号", "3");
map.put("合肥四号", "3");
map.put("合肥五号", "3");

map.put("南京一号", "5");
map.put("南京二号", "5");
map.put("南京三号", "5");
map.put("南京四号", "5");
map.put("南京五号", "5");

int sum=0;
for(String key: map.keySet()){
sum+=Integer.parseInt(map.get(key));
System.out.println(key + " : " + map.get(key));
}
System.out.println("sum : " + sum);
System.out.println("******************************");

Map resultMap = sortMapByKey(map); //按Key进行排序
for (Map.Entry entry : resultMap.entrySet()) 
{
System.out.println(entry.getKey() + " " + entry.getValue());
}
}


public static Map sortMapByKey(Map map){
if(map == null || map.isEmpty()){
return null;
}
Map sortMap = new TreeMap(new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
}


MapKeyComparator.java 文件

package com.yang.selenium;

import java.util.Comparator;

public class MapKeyComparator implements Comparator{
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
}

你可能感兴趣的:(自动化测试)