首页 > 解决方案 > 有没有办法在超类的方法之前将类变量放入 testNG

问题描述

我在 class1 中有 @test 方法,在超类中有 @before 方法。我想在 @before 方法中访问在 class1 中声明的类变量。

标签: testngtestng-annotation-test

解决方案


可以使用反射访问实例变量和类变量。虽然这不是推荐的方式(如共享的评论所述)。

您可以在 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

推荐阅读