`

TestNG参数化测试之支持数据对象

阅读更多

 

本文描述如何从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)

 总结:此代码有如下几点限制

  1. User类跟测试类ObjectTest以及ObjectTest.xls必须在同一个包下面
  2. User类只能存储基本数据类型,并且读出来的总是String

 

 

 

  • 大小: 12.1 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics