TestNG-使用ITestContext共享数据

1,329 阅读1分钟

image.png

令我不爽Apache Common Chain

我们希望实现用例间的数据共享,因为上一个用例执行完的返回值,可能正是下个用例需要的输入数据。 本来是用Chain实现的,但是令我不爽的是每个命令Command要新建一个Class。我们希望实现关键字驱动,如果一个关键字一个Class,并且关键字写得比较小,那简直是灾难啊……

image.png

方法1:使用TestNG的Depend

image.png

我试了下,如果定义了类成员变量,哪怕不用depend,照样可以取到值。缺点是必须在类里面定义一个对象。

方法2:使用ITestContext

image.png

这篇文章里,对ITestContext有更多解释,并且提供了一个登陆、获取token的例子,非常好!

www.ontestautomation.com/using-the-t…

**Since the ITestContext is created once and remains active for the duration of your test run, this is the perfect way to implement object sharing in your test suite. **

我写的实例:

import org.testng.ITestContext;
import org.testng.annotations.Test;

public class Demo {
    @Test
    public void keyword(ITestContext context){
        context.setAttribute("demoString", "Test Passing Value.");
    }

    @Test
    public void keywordPass(ITestContext context){
        System.out.println(context.getAttribute("demoString"));
    }
}

stackoverflow.com/questions/3… www.programcreek.com/java-api-ex… rationaleemotions.wordpress.com/2014/02/13/…