TestNG中的另一个有趣的功能是参数化测试。 在大多数情况下,您会遇到业务逻辑需要大量测试的场景。 参数化测试允许开发人员使用不同的值一次又一次地运行相同的测试。

TestNG可以通过两种不同的方式将参数直接传递给测试方法:

使用testng.xml

使用数据提供者

在本教程中,我们将向您展示如何通过XML

为了方便演示,这里创建一个名称为:ParameterTest 的 Maven 工程,其结构如下所示 -

1. 使用XML传递参数

在此示例中,filename属性从testng.xml传递,并通过

依懒文件:pom.xml 文件代码如下所示 -

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.yiibai

IgnoreTest

0.0.1-SNAPSHOT

jar

IgnoreTest

http://maven.apache.org

UTF-8

org.testng

testng

6.8.7

test

junit

junit

3.8.1

test

mysql

mysql-connector-java

6.0.2

compile

创建一个名称为:TestParameterXML.java,其代码如下所示 -

package com.yiibai;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.URL;

import java.sql.Connection;

import java.sql.DriverManager;

import java.util.Properties;

import org.testng.annotations.Parameters;

import org.testng.annotations.Test;

public class TestParameterXML {

Connection con;

@Test

@Parameters({ "dbconfig", "poolsize" })

public void createConnection(String dbconfig, int poolsize) {

System.out.println("dbconfig : " + dbconfig);

System.out.println("poolsize : " + poolsize);

Properties prop = new Properties();

InputStream input = null;

try {

// get properties file from project classpath

String path = System.getProperty("user.dir")+"\\"+dbconfig;

System.out.println("path => "+path);

//input = getClass().getClassLoader().getResourceAsStream(path);

//prop.load(input);

prop.load(new FileInputStream(dbconfig));

String drivers = prop.getProperty("jdbc.driver");

String connectionURL = prop.getProperty("jdbc.url");

String username = prop.getProperty("jdbc.username");

String password = prop.getProperty("jdbc.password");

System.out.println("drivers : " + drivers);

System.out.println("connectionURL : " + connectionURL);

System.out.println("username : " + username);

System.out.println("password : " + password);

Class.forName(drivers);

con = DriverManager.getConnection(connectionURL, username, password);

} catch (Exception e) {

//e.printStackTrace();

} finally {

if (input != null) {

try {

input.close();

} catch (IOException e) {

//e.printStackTrace();

}

}

}

}

}

创建一个名称为:db.properties 的文件, 其代码如下所示 -

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/test

jdbc.username=root

jdbc.password=123456

创建一个名称为:testng.xml 的文件, 其代码如下所示 -

执行上面测试类代码,得到以下结果 -

[TestNG] Running:

F:\worksp\testng\ParameterTest\src\main\java\com\yiibai\testng.xml

dbconfig : db.properties

poolsize : 10

path => F:\worksp\testng\ParameterTest\db.properties

drivers : com.mysql.jdbc.Driver

connectionURL : jdbc:mysql://localhost:3306/test

username : root

password : 123456

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

Tue May 02 23:11:05 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

===============================================

test-parameter

Total tests run: 1, Failures: 0, Skips: 0

===============================================

2.1. 查看一个简单的int参数。

创建一个名称为:TestParameterDataProvider.java 的文件, 其代码如下所示 -

package com.yiibai;

import org.testng.Assert;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

public class TestParameterDataProvider {

@Test(dataProvider = "provideNumbers")

public void test(int number, int expected) {

Assert.assertEquals(number + 10, expected);

}

@DataProvider(name = "provideNumbers")

public Object[][] provideData() {

return new Object[][] { { 10, 20 }, { 100, 110 }, { 200, 210 } };

}

}

执行上面测试类代码,得到以下结果 -

[TestNG] Running:

C:\Users\Administrator\AppData\Local\Temp\testng-eclipse--1925148879\testng-customsuite.xml

PASSED: test(10, 20)

PASSED: test(100, 110)

PASSED: test(200, 210)

===============================================

Default test

Tests run: 3, Failures: 0, Skips: 0

===============================================

===============================================

Default suite

Total tests run: 3, Failures: 0, Skips: 0

===============================================

[TestNG] Time taken by org.testng.reporters.XMLReporter@1b40d5f0: 13 ms

[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@6ea6d14e: 34 ms

[TestNG] Time taken by org.testng.reporters.EmailableReporter2@4563e9ab: 7 ms

[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms

[TestNG] Time taken by org.testng.reporters.jq.Main@2aaf7cc2: 69 ms

[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@45c8e616: 4 ms

2.2.

创建一个名称为:TestParameterDataProvider2.java 的文件, 其代码如下所示 -

package com.yiibai;

import java.io.IOException;

import java.io.InputStream;

import java.util.HashMap;

import java.util.Map;

import java.util.Properties;

import org.testng.Assert;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

public class TestParameterDataProvider2 {

@Test(dataProvider = "dbconfig")

public void testConnection(Map map) {

for (Map.Entry entry : map.entrySet()) {

System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());

}

}

@DataProvider(name = "dbconfig")

public Object[][] provideDbConfig() {

Map map = readDbConfig();

return new Object[][] { { map } };

}

public Map readDbConfig() {

Properties prop = new Properties();

InputStream input = null;

Map map = new HashMap();

try {

input = getClass().getClassLoader().getResourceAsStream("db.properties");

prop.load(input);

map.put("jdbc.driver", prop.getProperty("jdbc.driver"));

map.put("jdbc.url", prop.getProperty("jdbc.url"));

map.put("jdbc.username", prop.getProperty("jdbc.username"));

map.put("jdbc.password", prop.getProperty("jdbc.password"));

} catch (Exception e) {

e.printStackTrace();

} finally {

if (input != null) {

try {

input.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return map;

}

}

执行上面测试类代码,得到以下结果 -

[TestNG] Running:

F:\worksp\testng\ParameterTest\src\main\java\com\yiibai\testng.xml

dbconfig : db.properties

poolsize : 10

path => F:\worksp\testng\ParameterTest\db.properties

drivers : com.mysql.jdbc.Driver

connectionURL : jdbc:mysql://localhost:3306/test

username : root

password : 123456

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

Tue May 02 23:15:52 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

===============================================

test-parameter

Total tests run: 1, Failures: 0, Skips: 0

===============================================

此示例显示如何根据测试方法名称传递不同的参数。

创建一个名称为:TestParameterDataProvider3.java 的文件, 其代码如下所示 -

package com.yiibai;

import java.lang.reflect.Method;

import org.testng.Assert;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

public class TestParameterDataProvider3 {

@Test(dataProvider = "dataProvider")

public void test1(int number, int expected) {

Assert.assertEquals(number, expected);

}

@Test(dataProvider = "dataProvider")

public void test2(String email, String expected) {

Assert.assertEquals(email, expected);

}

@DataProvider(name = "dataProvider")

public Object[][] provideData(Method method) {

Object[][] result = null;

if (method.getName().equals("test1")) {

result = new Object[][] {

{ 1, 1 }, { 200, 200 }

};

} else if (method.getName().equals("test2")) {

result = new Object[][] {

{ "test@gmail.com", "test@gmail.com" },

{ "test@yahoo.com", "test@yahoo.com" }

};

}

return result;

}

}

执行上面测试类代码,得到以下结果 -

[TestNG] Running:

C:\Users\Administrator\AppData\Local\Temp\testng-eclipse-817554174\testng-customsuite.xml

PASSED: test1(1, 1)

PASSED: test1(200, 200)

PASSED: test2("test@gmail.com", "test@gmail.com")

PASSED: test2("test@yahoo.com", "test@yahoo.com")

===============================================

Default test

Tests run: 4, Failures: 0, Skips: 0

===============================================

===============================================

Default suite

Total tests run: 4, Failures: 0, Skips: 0

===============================================

[TestNG] Time taken by org.testng.reporters.XMLReporter@1b40d5f0: 17 ms

[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@6ea6d14e: 51 ms

[TestNG] Time taken by org.testng.reporters.EmailableReporter2@4563e9ab: 9 ms

[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms

[TestNG] Time taken by org.testng.reporters.jq.Main@2aaf7cc2: 93 ms

[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@45c8e616: 5 ms

4. @DataProvider + ITestContext

在TestNG中,我们可以使用org.testng.ITestContext来确定调用当前测试方法的运行时参数。 在最后一个例子中,我们将演示如何根据包含的分组名称传递参数。

创建一个名称为:TestParameterDataProvider4.java 的文件, 其代码如下所示 -

package com.yiibai;

import org.testng.Assert;

import org.testng.ITestContext;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

public class TestParameterDataProvider4 {

@Test(dataProvider = "dataProvider", groups = {"groupA"})

public void test1(int number) {

Assert.assertEquals(number, 1);

}

@Test(dataProvider = "dataProvider", groups = "groupB")

public void test2(int number) {

Assert.assertEquals(number, 2);

}

@DataProvider(name = "dataProvider")

public Object[][] provideData(ITestContext context) {

Object[][] result = null;

//get test name

//System.out.println(context.getName());

for (String group : context.getIncludedGroups()) {

System.out.println("group : " + group);

if ("groupA".equals(group)) {

result = new Object[][] { { 1 } };

break;

}

}

if (result == null) {

result = new Object[][] { { 2 } };

}

return result;

}

}

创建一个名称为:testng4.xml 的文件, 其代码如下所示 -

执行上面测试类代码,得到以下结果 -

[TestNG] Running:

F:\worksp\testng\ParameterTest\src\main\java\com\yiibai\testng4.xml

group : groupA

===============================================

test-parameter

Total tests run: 1, Failures: 0, Skips: 0

===============================================

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

testng执行参数_TestNG参数化测试相关推荐

  1. testng执行参数_TestNG中注解使用 笔记

    一.Before和After类注解 1.@BeforeSuite.@AfterSuite 2.@BeforeTest.@AfterTest 3.@BeforeClass.@AfterClass 4.@ ...

  2. java参数化测试除法_TestNG - 参数化测试( Parameterized Test)

    TestNG - 参数化测试( Parameterized Test) TestNG中另一个有趣的功能是parametric testing . 在大多数情况下,您会遇到业务逻辑需要大量不同测试的情况 ...

  3. testng执行参数_初识TestNG测试框架

    testkuaibao|软件测试自学公众号 公众号文章的推送机制改变.又由于我们公众号是不定时更新的,所以会导致很多小伙伴不能及时的收到我们的文章.大家可以把我们的公众号设置为星标,或者看完文章点个在 ...

  4. 参数化测试 junit_JUnit 5 –参数化测试

    参数化测试 junit JUnit 5令人印象深刻,尤其是当您深入研究扩展模型和体系结构时 . 但是从表面上讲,编写测试的地方,开发的过程比革命的过程更具进化性 – JUnit 4上没有杀手级功能吗? ...

  5. JUnit 5 –参数化测试

    JUnit 5令人印象深刻,尤其是当您深入研究扩展模型和体系结构时 . 但是从表面上讲,编写测试的地方,开发的过程比革命的过程更具进化性 – JUnit 4上没有杀手级功能吗? 幸运的是,至少有一个: ...

  6. testng入门教程10 TestNG参数化测试

    在TestNG的另一个有趣的功能是参数测试.在大多数情况下,你会遇到这样一个场景,业务逻辑需要一个巨大的不同数量的测试.参数测试,允许开发人员运行同样的测试,一遍又一遍使用不同的值. TestNG让你 ...

  7. 浅谈Junit4和TestNG中的参数化测试

    最近在看Junit4的相关知识,由于本身做的是自动化方面的测试,所以工作上着重于应用TestNG.恰好遇到了一个将case进行参数化的需求,故在此记录Junit4和TestNG在参数化方面的区别. 一 ...

  8. TestNG参数化测试

    在TestNG的另一个有趣的功能是参数测试.在大多数情况下,你会遇到这样一个场景,业务逻辑需要一个巨大的不同数量的测试.参数测试,允许开发人员运行同样的测试,一遍又一遍使用不同的值. TestNG让你 ...

  9. 参数化测试 junit_JUnit参数化测试

    参数化测试 junit JUnit Parameterized Tests allow us to run a test method multiple times with different ar ...

最新文章

  1. java run_javarun
  2. 【 English 】与个人品质有关的英语词汇
  3. 首个64层3D NAND闪存技术出现
  4. 患者信息SQL v1
  5. C#,pdf文件转换成图片文件。
  6. GraphQL:面对复杂类型
  7. 线程池默认多少个线程_我需要多少个线程?
  8. Less or Equal(CF-977C)
  9. javascript map 排序_1Keys仅用1 kb的JavaScript制作钢琴
  10. Spark的RDD检查点实现分析
  11. anaconda中更改python版本
  12. Java --人民币(RMB)小写/数字转换大写工具类
  13. 时间序列(二):时间序列平稳性检测
  14. 实时音频编解码之七 预加重
  15. dpdk介绍系列之ring
  16. 高中关于人工智能方面的课题_人工智能的课题有什么研究方向
  17. 学习使用github(一)
  18. IDEA同时同步代码到GitHub和Gitee
  19. 安卓手机使用什么便签?
  20. LiveNVR监控流媒体Onvif/RTSP功能功能-支持GB35114接入国标流媒体平台接入说明

热门文章

  1. 用scrapy框架爬取微博所有人的微博内容的
  2. python趣味编程-2048游戏
  3. Windows7农行网银页面无法显示问题的解决方法
  4. 远程连接服务器 Network error:Connection refused
  5. 中国工程机械加速布局万亿赛道 中联重科等巨头“狂飙”海外
  6. vscode ImportError: No module named xxx
  7. 使用localStorage统计页面停留时间
  8. PHP中间件是什么?
  9. 全国计算机有一级学科博士点的学校,拥有一级学科博士点能否说明一个学校的这个专业较强?...
  10. 高等数学第一章第一节--函数与极限