Home Java javaTutorial Introduction to TestNG Data Driven

Introduction to TestNG Data Driven

Aug 26, 2019 pm 04:19 PM
java

TestNG数据驱动

testng的功能很强大,利用@DataProvider可以做数据驱动,数据源文件可以是EXCEL,XML,YAML,甚至可以是TXT文本。

Introduction to TestNG Data Driven

@DataProvider注解简介:

@DataProvider标记专门为测试方法提供参数的方法。这类方法必须返回Object[ ][ ]类型的二维数组或者Iterator[],每一行的Object[],都是测试方法的一个测试数据集,测试方法会为每个测试数据集执行一次。如果没有指定参数的名称,则默认为方法的名称,方法的名称没有限制。

@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);
    }
}
Copy after login

如上所示@DataProvider注解了createUser方法,返回的二位数组里有三行数据,每行两列。

所以@Test(dataProvider = "user")注解的verifyUser方法有两个参数,用来接收每一行的两个数据,如果createUser返回的数据数组的列数和verifyUser的参数个数不同就会报错的。

因为返回的有三行,所以verifyUser会被执行三次。结果如下:

PASSED: verifyUser("root", "root")
FAILED: verifyUser("test", "root")
PASSED: verifyUser("test", "test")
Copy after login

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");
    }
}
Copy after login

这个类实现了Iterator迭代器,TestNG调用此类实现的hasNext()、next()方法得到一行数据,在next()方法中可以看到,我把数据是放在Map中的,再把map放在Object[]里,所以测试方法的参数就必须是一个Map。我这里改成了只读取一行,因为一个csv文件的一个caseId只应该有一行。

数据驱动类:

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());
    }
}
Copy after login

Method方法是通过反射获取的,总之哪个方法调用我Method就是那个方法。

method.getDeclaringClass().getSimpleName()可以获取方法所属的类的类名。

我这里规定了csv的文件名就是测试类的类名,用例名就是方法名。

return (Iterator) new CSVData(…)就是将CSV读取类读取的结果返回,返回的类型是Iterator的,符合@DataProvider的返回值类型要求。当@Test(dataProvider = "dataSource")注解的测试方法执行时就会调用Iterator的hasNext()判断是否有数据和next()获取数据。

测试类:

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);
    }
}
Copy after login

输出结果如下:

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})
Copy after login

总结

通过以上例子可以看到,无论@DataProvider注解的方法返回的是Object[ ][ ]还是Iterator[],最后测试方法获得的参数都是Object[ ]里放的东西,第一个例子里放了两列String,第二个例子里放了Map,所以第一个测试类的测试方法的参数是两个String,第二个测试类的测试方法的参数是Map,必须保持一致才行。

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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 vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

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 vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

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.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

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

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

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

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

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.

See all articles