Introduction to TestNG Data Driven
TestNG数据驱动
testng的功能很强大,利用@DataProvider可以做数据驱动,数据源文件可以是EXCEL,XML,YAML,甚至可以是TXT文本。
@DataProvider注解简介:
@DataProvider标记专门为测试方法提供参数的方法。这类方法必须返回Object[ ][ ]类型的二维数组或者Iterator
@DataProvider的小例子:
import java.lang.reflect.Method; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class test { @DataProvider(name = "user") public Object[][] createUser(Method m) { System.out.println(m.getName()); return new Object[][] { { "root", "root" }, { "test", "root" }, { "test", "test" } }; } @Test(dataProvider = "user") public void verifyUser(String username, String password) { System.out.println("Verify User : " + username + ":" + password); assert username.equals(password); } }
如上所示@DataProvider注解了createUser方法,返回的二位数组里有三行数据,每行两列。
所以@Test(dataProvider = "user")注解的verifyUser方法有两个参数,用来接收每一行的两个数据,如果createUser返回的数据数组的列数和verifyUser的参数个数不同就会报错的。
因为返回的有三行,所以verifyUser会被执行三次。结果如下:
PASSED: verifyUser("root", "root") FAILED: verifyUser("test", "root") PASSED: verifyUser("test", "test")
CSV文件数据读取和@DataProvider
我自己做了一个以csv为例的测试架子,部分代码可通用。
CSV文件读取类(可通用,目录自己可以修改,也可改变成读取EXCEL、TXT等文件):
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; public class CSVData implements Iterator<Object[]> { private BufferedReader br = null; //行数 private int rowNum = 0; //获取次数 private int curRowNo = 0; //列数 private int columnNum = 0; //key名 private String[] columnName; //csv中所有行数据 private List<String> csvList; //实际想要的行数据 private List<String> csvListNeed; /* * 在TestNG中由@DataProvider(dataProvider = "name")修饰的方法 * 取csv时,调用此类构造方法(此方法会得到列名并将当前行移到下以后)执行后,转发哦 * TestNG自己的方法中去,然后由它们调用此类实现的hasNext()、next()方法 * 得到一行数据,然后返回给由@Test(dataProvider = "name")修饰的方法,如此 * 反复到数据读完为止 * * * @param filepath CSV文件名 * @param casename 用例名 */ public CSVData(String fileName, String caseId) { try { File directory = new File("."); String ss = "resources."; File csv = new File(directory.getCanonicalFile() + "\\src\\test\\" + ss.replaceAll("\\.", Matcher.quoteReplacement("\\")) + fileName + ".csv"); br = new BufferedReader(new FileReader(csv)); csvList = new ArrayList<String>(); while (br.ready()) { csvList.add(br.readLine()); this.rowNum++; } String stringValue[] = csvList.get(0).split(","); this.columnNum = stringValue.length; columnName = new String[stringValue.length]; for (int i = 0; i < stringValue.length; i++) { columnName[i] = stringValue[i].toString(); } this.curRowNo++; csvListNeed = new ArrayList<String>(); for (int i = 1; i < rowNum; i++) { String values[] = csvList.get(i).split(","); if (caseId.equals(values[0])) { csvListNeed.add(csvList.get(i)); } } this.rowNum = 2;//就取一行 } catch (Exception e) { e.printStackTrace(); } } @Override public boolean hasNext() { if (this.rowNum == 0 || this.curRowNo >= this.rowNum) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } return false; } else { return true; } } @Override public Object[] next() { /* * 将数据放入map */ Map<String, String> s = new TreeMap<String, String>(); String csvCell[] = csvListNeed.get(0).split(","); for (int i = 0; i < this.columnNum; i++) { String temp = ""; try { temp = csvCell[i].toString(); } catch (ArrayIndexOutOfBoundsException ex) { temp = ""; } s.put(this.columnName[i], temp); } Object r[] = new Object[1]; r[0] = s; this.curRowNo++; return r; } @Override public void remove() { throw new UnsupportedOperationException("remove unsupported"); } }
这个类实现了Iterator
数据驱动类:
import java.lang.reflect.Method; import java.util.Iterator; import org.testng.annotations.DataProvider; public class DataProviderTest { /** * @DataProvider的返回值类型只能是Object[][]与Iterator<Object>[] * * @param method * @return */ @DataProvider public Iterator<Object[]> dataSource(Method method) { return (Iterator<Object[]>) new CSVData(method.getDeclaringClass().getSimpleName(), method.getName()); } }
Method方法是通过反射获取的,总之哪个方法调用我Method就是那个方法。
method.getDeclaringClass().getSimpleName()可以获取方法所属的类的类名。
我这里规定了csv的文件名就是测试类的类名,用例名就是方法名。
return (Iterator
测试类:
import java.util.Map; import org.testng.annotations.Test; public class DataTest extends DataProviderTest { @Test(dataProvider = "dataSource") public void id2(Map<String, String> data) { System.out.println(data); } @Test(dataProvider = "dataSource") public void id1(Map<String, String> data) { System.out.println(data); } }
输出结果如下:
PASSED: id1({caseId=id1, flag=Y, property=flowModel, type=com.mybank.bkloanapply.core.model.BaseModel, value=BaseModel.csv@1}) PASSED: id2({caseId=id2, flag=M, property=context, type=java.util.Map, value=a:Object.csv@1})
总结
通过以上例子可以看到,无论@DataProvider注解的方法返回的是Object[ ][ ]还是Iterator
The above is the detailed content of Introduction to TestNG Data Driven. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
