Junit/TestNg cucumber testNG 在步骤间数据如何传递

lyyyyyyy · 2023年02月22日 · 最后由 lyyyyyyy 回复于 2023年02月23日 · 4713 次阅读

这是我写的一个 Demo
feature 文件

Feature: Demo1

  @Smoke1
  Scenario Outline: demo Test
    Given go to "<url>"
    And print person
    Examples:
      | url                   |
      | https://www.baidu.com |
      | https://www.sina.com  |
      | https://www.qq.com    |

步骤定义类

public class MyStepdefs {

    Person1 person1 = new Person1();

    @Given("^go to \"([^\"]*)\"$")
    public void goTo(String arg0) {
        person1.setName(arg0);
        System.out.println(arg0);
    }

    @And("^print person$")
    public void printPerson() {
        String name = person1.getName();
        System.out.println("name = " + name);
    }

}
class Person1{
    String name;

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person1{" +
                "name='" + name + '\'' +
                '}';
    }

    public void setName(String name) {
        this.name = name;
    }
}

运行结果

https://www.baidu.com
name = null

https://www.sina.com
name = null

https://www.qq.com
name = null

虽然可以通过设置成 static 的方式解决,但是如果多线程也是会有问题的。看到网上用 cucumber-picoContainer 来解决,但是尝试后还是一样,不知道大佬们有遇到过类似的问题吗?

共收到 8 条回复 时间 点赞

请教了大佬之后用 ThreadLocal 可以很好的解决这个问题😀

少年 chatgpt 最近体验的一些心得 中提及了此贴 02月23日 11:45
lyyyyyyy 回复

是的,所以我一般走手动组装,当然楼上几个回复都不错的,你也可以参考😃

Eason 回复

单例如果步骤较长,数据肯定会混乱

fiskeryang 回复

谢谢,我试试

少年 回复

还得是你,为啥我进去一直是 1020

可以通过 new TestNG() 来组装套件和 case,自己实现参数传递都可以。再不行放到单例里面 get set😅

testng 本身可以通过 ITestContext 接口来实现上下文数据传递

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册