testng - 有没有办法在超类的方法之前将类变量放入 testNG
问题描述
我在 class1 中有 @test 方法,在超类中有 @before 方法。我想在 @before 方法中访问在 class1 中声明的类变量。
解决方案
可以使用反射访问实例变量和类变量。虽然这不是推荐的方式(如共享的评论所述)。
您可以在 testng 中使用已经实现的依赖注入,使用谷歌的guice
库@Before
和@After
钩子。分享一个相同的例子:
public class Test extends BaseTest {
String stringOne = "INTER";
static final String stringTwo = "MISSION";
@Test(testName = "Sample Test")
private void reflection_test() {
System.out.println("-----INSIDE THE SUB CLASS-----");
System.out.println(stringOne + stringTwo);
}
}
现在在@Before
基类中的 which 中,我们将ITestResult
作为参数添加到方法中(您可以在此处阅读有关 testng 的依赖注入的信息)。
现在使用ITestResult
参数,我们可以得到测试类,然后可以使用Java反射来获取实例化的类对象、字段、方法等。检查以下示例:
public class BaseTest {
@BeforeMethod(alwaysRun = true)
public void init(ITestResult result) throws IllegalAccessException {
Class clazz = result.getTestClass().getRealClass();
System.out.println("-----THIS IS FROM THE PARENT CLASS-----");
for (Field f : clazz.getDeclaredFields()) {
System.out.println("Variable Value : " + f.get(this));
}
System.out.println();
}
}
在执行测试时,我们将收到以下输出:
-----THIS IS FROM THE PARENT CLASS-----
Variable Value : INTER
Variable Value : MISSION
-----INSIDE THE SUB CLASS-----
INTERMISSION
推荐阅读
- r - 是否有一个函数可以过滤包含字符串的行,但在包含 R 中给定字符串的选定列名称上?
- javascript - 我无法显示来自本地 API 的数据
- php - 如何展示孩子
- sql - 如果结果为真,则返回列名
- c# - SqlDataAdapter.SelectCommand 没有返回正确的结果
- spring-boot-data-geode - 在@EnableClusterDefinedRegions 之后将@Resource 用于Geode 区域
- material-components-android - 当用户从 NestedScrollView 中启动拖动时,BottomSheet 没有拖动阈值
- ajax - Sails.js 中未触发 Ajax 表单操作
- mysql - MySQL 不准确的计算与平均和日期时间
- python - 来自 GMAIL 编码问题的 Python IMAP