如何在TestNG中将变量从BeforeTest传递到Test注解?
一个TestNG类可以包含各种TestNG方法,例如@BeforeTest,@AfterTest, @BeforeSuite, @BeforeClass, @BeforeMethod, @test等。在许多情况下,我们需要将一些变量从这些方法传递到主要的@Test方法。由于这些方法都不支持return类型,所以传递变量的最佳方法是使用类/实例变量,而不是局部变量。
类/实例变量的作用域在整个类中。因此,在@BeforeTest或@BeforeMethod中设置的任何值都可以在@Test方法中使用。
在本文中,我们将学习如何在TestNG中将变量从@BeforeTest传递到@Test注解。
解决此问题的方法/算法
步骤1 - 创建一个TestNG类NewTestngClass并声明一个名为employeeName的变量。
步骤2 - 在@BeforeTest中写入以下代码:
public void name() {
employeeName = "Ashish";
System.out.println("employeeName is: "+employeeName);
}步骤3 - 在NewTestngClass类中编写一个@Test方法,并使用代码中描述的变量employeeName。
步骤4 - 现在创建如下所示的testNG.xml来运行TestNG类。
步骤5 - 最后,运行testNG.xml或直接在IDE中运行TestNG类,或者使用命令行编译并运行它。
示例
以下是常用TestNG类NewTestngClass的代码:
src/ NewTestngClass.java
import org.testng.annotations.*;
public class NewTestngClass {
String employeeName;
// test case 1
@Test()
public void testCase1() throws InterruptedException {
System.out.println("in test case 1 of NewTestngClass");
String employeeFullName = employeeName + " Anand";
System.out.println("employeeFullName is: "+employeeFullName);
}
@BeforeTest
public void name() {
employeeName = "Ashish";
System.out.println("employeeName is: "+employeeName);
}
}testng.xml
这是一个配置文件,用于组织和运行TestNG测试用例。当只需要执行有限的测试而不是完整的套件时,它非常方便。
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Suite1">
<test name = "test1">
<classes>
<class name = "NewTestngClass"/>
</classes>
</test>
</suite>输出
employeeName is: Ashish in test case 1 of NewTestngClass employeeFullName is: Ashish Anand =============================================== Suite1 Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 ===============================================
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP