本文描述如何从Excel中读取数据然后传递给TestNG的测试方法,此次增加了数据对象的支持。
当需要向TestNG的测试方法传递如下多列数据的时候:
我们当然不希望在测试方法为每列数据增加一个参数,我们会希望使用testObject(String caseName, String salesId, User u)这样的形式去运行测试方法,User类是一个普通的JAVABean:
public class User { private String userId; private String firstName; private String LastName; private String institution; private String country; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return LastName; } public void setLastName(String lastName) { LastName = lastName; } public String getInstitution() { return institution; } public void setInstitution(String institution) { this.institution = institution; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }
以下是完整的测试类ObjectTest:
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.ssgm.ssa.umt.utilities.ExcelReader; public class ObjectTest { @DataProvider(name = "objectTest") public Object[][] createData(){ return ExcelReader.getRunDataObject(this.getClass(), ""); } @Test(dataProvider = "objectTest") public void testObject(String caseName, String salesId, User u){ System.out.println("******The Test is started******"); System.out.println("The Test Case Name is: " + caseName); System.out.println("The SalesID is: " + salesId); System.out.println("The First Name is: " + u.getFirstName()); System.out.println("******The Test is ended******"); } }
注意:Excel文件必须与测试类同名,并且放在同一个包下面
以下是ExcelReader的具体实现:
public class ExcelReader { @SuppressWarnings("unchecked") public static Object[][] getRunDataObject(Class testClass, String env){ List<Object[]> results = new ArrayList<Object[]>(); try { URL resource = testClass.getResource(testClass.getSimpleName()+".xls"); System.out.println("++++" + resource.getPath()); File file = new File(resource.getPath().replaceAll("%20", " ")); FileInputStream fis = new FileInputStream(file); POIFSFileSystem POIStream = new POIFSFileSystem(fis); HSSFWorkbook workBook = new HSSFWorkbook(POIStream); HSSFSheet sheet = workBook.getSheetAt(0); if ((env.equalsIgnoreCase("dev"))||(env.equalsIgnoreCase("uat"))||(env.equalsIgnoreCase("prod"))){ sheet = workBook.getSheet(env); } int rowSize = sheet.getLastRowNum(); HSSFRow headRow = sheet.getRow(0); int colSize = headRow.getLastCellNum(); int objectSize = getObjectSize(headRow); System.out.println("The row size is: " + rowSize); System.out.println("The column size is: " + colSize); System.out.println("The Object size is: " + objectSize); for (int rowIndex =1; rowIndex <= rowSize; rowIndex++ ) { HSSFRow row = sheet.getRow(rowIndex); HSSFCell lastcell = row.getCell(colSize-1); if (lastcell.getStringCellValue().equalsIgnoreCase("n")){ continue; } Object[] objects = new Object[objectSize]; int objectIndex = -1; String className = null; String fieldName = null; String setMethodName = null; Object o = null; Class c = null; Method[] methods = null; String currColName = null; String preColName = null; for (int columnIndex=0; columnIndex < colSize-1 ; columnIndex++){ String currCellString = getValueByColunmIndex(row, columnIndex); currColName = getColumnName(headRow, columnIndex) ; if (columnIndex >0) preColName = getColumnName(headRow, columnIndex-1); boolean isNewObject = isNewObject(currColName, preColName); boolean isClass = isClass(currColName); System.out.println("========The current Column Name is: " + currColName); System.out.println("========Is current new Object? " + isNewObject); System.out.println("========Is current a Class: " + isClass); if (isClass){ className = currColName.split("\\.")[0]; fieldName = currColName.split("\\.")[1]; setMethodName = "set" + fieldName.toLowerCase(); String packageName = testClass.getPackage().getName(); c = Class.forName(packageName + "."+ className); methods = c.getDeclaredMethods(); System.out.println("+++The current Class name is: " + className); System.out.println("+++The current Field name is: " + fieldName); System.out.println("+++The current setMethodName is: " + setMethodName); } // There are two kinds of New Object // 1. The column header likes "commonString", isClass flag will be false // 2. The column header likes "User.firstField", isClass flag will be true if (isNewObject){ ++objectIndex; if (isClass){ try { o = c.newInstance(); for (Method method : methods) { String methodName = method.getName().toLowerCase(); System.out.println("++The current Method name is: " + methodName); if (methodName.equals(setMethodName)){ method.invoke(o, currCellString); System.out.println("-------Sucessfully " + setMethodName); break; } } objects[objectIndex] = o; } catch (Exception e) { System.out.println("The Class Name Not Found: com.ssgm.gmo.unit." + className); } } else { // when it's new common String and not a class objects[objectIndex] = currCellString; } } else { // When it's a existing Object, the column name is like "User.seondCol" for (Method method : methods) { if (method.getName().toLowerCase().equals(setMethodName)){ method.invoke(o, currCellString); System.out.println("-------Sucessfully " + setMethodName); break; } } objects[objectIndex] = o; } } results.add(objects); } fis.close(); } catch (IOException e) { e.printStackTrace(); }catch (ClassNotFoundException e) { e.printStackTrace(); }catch (IllegalArgumentException e) { e.printStackTrace(); }catch (IllegalAccessException e) { e.printStackTrace(); }catch (InvocationTargetException e) { e.printStackTrace(); } Object[][] returnArray = new Object[results.size()][]; for (int i = 0; i < returnArray.length; i++) { returnArray[i] = (Object[]) results.get(i); } return returnArray; } private static int getObjectSize(HSSFRow row){ int colSize = row.getLastCellNum(); int objectSize = 0; Set<String> set = new HashSet<String>(); String columnName = null; for (int columnIndex=0; columnIndex < colSize ; columnIndex++) { columnName = getValueByColunmIndex(row, columnIndex); System.out.println("Current Column Name is: " + columnName); if (isClass(columnName)) set.add(columnName.split("\\.")[0]); else set.add(columnName); } objectSize = set.size()- 1; return objectSize; } private static String getColumnName(HSSFRow headRow, int index){ return getValueByColunmIndex(headRow, index); } private static boolean isNewObject(String curr, String pre) { boolean flag = false; if (pre == null) flag = true; else if (!isClass(curr)) { flag = true; } else if (pre.contains(curr.split("\\.")[0])){ flag = false; } else flag = true; return flag; } private static boolean isClass(String columnName) { return columnName.contains("."); } private static String getValueByColunmIndex(HSSFRow row, int cIndex){ String value = ""; HSSFCell cell = row.getCell(cIndex); if (cell != null) { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); if (date != null) { value = new SimpleDateFormat("yyyy-MM-dd").format(date); } else { value = ""; } } else { value = new DecimalFormat("0").format(cell.getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_FORMULA: if (!cell.getStringCellValue().equals("")) { value = cell.getStringCellValue(); } else { value = cell.getNumericCellValue() + ""; } break; case HSSFCell.CELL_TYPE_BLANK: break; case HSSFCell.CELL_TYPE_ERROR: value = ""; break; case HSSFCell.CELL_TYPE_BOOLEAN: value = (cell.getBooleanCellValue() == true ? "Y" : "N"); break; default: value = "default"; } } return value; } }
运行测试之后Console的输出如下:
******The Test is started****** The Test Case Name is: 01.add client success The SalesID is: salesOne The First Name is: AutoAddClient32 ******The Test is ended****** ******The Test is started****** The Test Case Name is: 02.add client failed The SalesID is: salesTwo The First Name is: AutoAddMonday1Client ******The Test is ended****** PASSED: testObject("01.add client success", "salesOne", com.ssgm.gmo.unit.User@ef137d) PASSED: testObject("02.add client failed", "salesTwo", com.ssgm.gmo.unit.User@17e4ca)
总结:此代码有如下几点限制
- User类跟测试类ObjectTest以及ObjectTest.xls必须在同一个包下面
- User类只能存储基本数据类型,并且读出来的总是String
相关推荐
ant+selenium+testng自动化测试方案
仅仅用于初学者交流,意在与自动化测试初学者进行相互学习交流,简单的实现了java+selenium+testng参数化打开百度搜索
java+selenium+maven+testng自动化测试框架实例(实际项目)
Selenium+TestNG自动化测试
TestNG-Abbot源自于两个成功的开发人员测试框架的结合:Abbot和TestNG。Abbot是一种JUnit扩展框架,主要目的是使GUI组件实现编程隔离,它还提供了一种验证GUI行为的简易方法。TestNG-Abbot是一种测试框架,它为GUI...
自己整理的使用Appium+TestNG实现的Android自动化测试。包括安装配置、真机测试说明和一个简单的Android App源码、一个针对该App的测试
适用于想了解TestNG测试的同学
1、testng测试报告模板BeautifulReport 2、testng.xml文件
开源自动化测试框架testng包,用于appium+java+android测试
全栈自动化测试实战 基于testng,httpclient,selenium.appium 书本上的东西
主要对举例对国家气象局接口自动化测试进行讲解(Get请求及结果断言),以达到自动化测试入门目的,需要有一定的JAVA知识(HTTP相关)。
Dagger-TestNG-selenium自动化测试可直接使用的工程包,支持多浏览器,直接在测试类中加代码即可
集成 Jenkins 和 TestNG 实现自助式自动化测试平台,测试可行,。
Selenium自动化测试框架视频-Testng使用介绍(自动化测试)
《Java测试新技术TestNG和高级概念》介绍了Java测试的新技术,主要内容包括:基本概念、测试设计模式、企业级测试、Java EE测试、集成和扩展TestNG等。《Java测试新技术TestNG和高级概念》通过针对有效测试Java应用...
selenium+java+testng+maven测试用例执行,testng执行
《Java测试新技术:TestNG和高级概念》介绍了Java测试的新技术,主要内容包括:基本概念、测试设计模式、企业级测试、Java EE测试、集成和扩展TestNG等。《Java测试新技术:TestNG和高级概念》通过针对有效测试Java...
Jenkins和TestNG搭建一个自助式的自动化测试平台。在软件业十分成熟的今天,敏捷(Agile)开发在业界日益流行,而面临的挑战也日益增多,不断变化的用户需求、缩短的开发周期、频繁的部署上线、复杂的产品架构和团队...
采用Maven+Selenium+TestNG+TestNG-xslt实现数据驱动自动化测试框架的实现,思想主要是采用PO模式进行代码封装以及对数据文件的读取使用。