TestNg
1.基本概念:
TestNG 是一个基于 Java 编写的测试框架,其名称来源于 "Next Generation"。它提供了多种功能以支持单元测试、集成测试和端到端测试,具有灵活的配置和强大的功能扩展性,是 JUnit 的一种进阶替代方案。以下是 TestNG 的一些主要特点和使用方法:
2.TestNG 的特点:
- 注解驱动:使用
@Test
、@BeforeClass
、@AfterMethod
等注解来管理测试方法的执行顺序和生命周期。- 支持并行测试:可以在 XML 配置中配置并行执行测试,以加快测试速度。
- 依赖测试:测试用例之间可以相互依赖(使用
dependsOnMethods
或dependsOnGroups
),可以控制测试的执行顺序。- 参数化测试:支持通过数据提供者(
@DataProvider
)传递参数。- 灵活的配置和分组:通过 TestNG XML 文件进行测试方法的分组与配置。
- 丰富的报告功能:自动生成 HTML 和 XML 格式的测试报告,并支持集成第三方工具(如 ReportNG)。
3.TestNG 基本注解:
public class TestExample {@BeforeSuitepublic void beforeSuite() {System.out.println("Executed before the entire suite.");}@BeforeClasspublic void beforeClass() {System.out.println("Executed before the first test method in the current class.");}@BeforeMethodpublic void beforeMethod() {System.out.println("Executed before each test method.");}@Testpublic void testMethod() {System.out.println("Test method executed.");}@AfterMethodpublic void afterMethod() {System.out.println("Executed after each test method.");}@AfterClasspublic void afterClass() {System.out.println("Executed after all test methods in the current class.");}@AfterSuitepublic void afterSuite() {System.out.println("Executed after the entire suite.");}
}
4.TestNG XML 配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="MySuite" parallel="methods" thread-count="3"><test name="MyTest"><classes><class name="com.example.TestExample" /></classes></test>
</suite>
parallel
属性:控制并行执行的级别,可以是 tests
、classes
或 methods
。
thread-count
属性:设置线程数量,决定并行测试时使用的最大线程数。
5.数据驱动测试(DataProvider)
TestNG 支持通过 @DataProvider
注解进行数据驱动测试,可以用来测试不同输入组合。以下是一个简单的数据驱动测试示例:
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;public class DataDrivenTest {@DataProvider(name = "testData")public Object[][] createData() {return new Object[][] {{ "data1", 1 },{ "data2", 2 }};}@Test(dataProvider = "testData")public void testMethod(String input, int number) {System.out.println("Input: " + input + ", Number: " + number);}
}
5.测试用例的依赖关系
使用 dependsOnMethods
可以设置测试用例的依赖关系
public class DependencyTest {@Testpublic void init() {System.out.println("Initialization completed.");}@Test(dependsOnMethods = "init")public void testMethod() {System.out.println("Test method executed after initialization.");}
}
6.TestNG 的并行测试
在 TestNG XML 中设置 parallel
属性,如:
<suite name="ParallelSuite" parallel="tests" thread-count="2">
使用 TestNG 注解 @Test(threadPoolSize = n)
来指定某个测试方法的线程池大小:
@Test(threadPoolSize = 3, invocationCount = 6)
public void parallelTest() {System.out.println("Executed by: " + Thread.currentThread().getId());
}
7.集成 Maven 与 TestNG
使用 Maven 时可以在 pom.xml
中添加 TestNG 依赖:
<dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>7.8.0</version><scope>test</scope>
</dependency>