【问题标题】:How can get argument values from @DataProvider for @Test in @Before and @AfterMethod anotation in TestNG如何从 @DataProvider 获取 @Before 中的 @Test 和 TestNG 中的 @AfterMethod 注释的参数值
【发布时间】:2020-11-26 06:28:55
【问题描述】:

我想从 TestNG 中的 @Test 获取参数名称及其值。这些参数由@DataProvider 提供。通常,当我想并行运行测试时,我可以将它存储在类的变量中,这不是一个好主意。这是我的代码:


import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestHomePage{

    @BeforeMethod(alwaysRun = true)
    public void setup(Method method) throws Exception {
        System.out.println("INFO ====setup===:" + method.getName());
        // how can I get parameters and value from @Test?
        //ex: sLogin="notLogin";sLike=""
    }

    @AfterMethod()
    public void tearnDown(Method method) {
        System.out.println("INFO ====tearnDown===:" + method.getName());
        // how can I get parameters and value from @Test?
    }

    @DataProvider(name = "likedata", parallel = true)
    public Object[][] likeDataprovider() throws Exception {
        return new Object[][] { { "notLogin", "" }, { "loggedIn", "notLike" }, { "loggedIn", "liked" } };
    }

    @Test(dataProvider = "likedata")
    public void verifyLikeFunction(String sLogin, String sLike, Method method) throws Exception {
        // Test
    }

}

谁能帮帮我?

谢谢。

【问题讨论】:

    标签: automated-tests testng dataprovider testng-dataprovider


    【解决方案1】:

    要获取值,请添加params作为@BeforeMethod的参数

     @BeforeMethod(alwaysRun = true)
        public void setup(Method method, Object[] params) throws Exception {
            System.out.println("INFO ====setup===:" + method.getName());
            
            System.out.println("Parameter value:");
            for (Object parameter : params) {
                System.out.println(parameter);
            }      
        }
    

    查看Dependency Injection in TestNG 了解更多信息。

    并获取参数名称,

      @BeforeMethod(alwaysRun = true)
        public void setup(Method method, Object[] params) throws Exception {
            System.out.println("Before , INFO ====setup===:" + method.getName());
           
            Parameter[] parameters= method.getParameters();
            
            System.out.println("Parameter names:");
            for (Parameter parameter : parameters) {
                System.out.println(parameter.getName());
            }     
        }
    

    如果在编译期间包含调试信息,则可以获取参数名称。详情请见this answer

    简单地说, 如果您使用的是 Eclipse,请转到项目 -> 属性 -> Java 编译器 -> 选中“存储有关方法参数的信息(可通过反射使用)

    我们可以在@AfterMethod 中做同样的事情。

    【讨论】:

    • 我尝试按照您所说的方式进行操作,但在阅读您的答案之前。无论如何,谢谢
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多