在 TestNG 中,依赖函数如何用于继承

in TestNG how is the dependonfunction works for the inheritance

假设我在下面定义了两个 class BaseClass 和 DerivedClass。 base等待1分钟,derived等待5分钟

class BaseClass {
    protected String getDatasetType() {
        return "BaseClass";
    }

    @BeforeClass
    public void initialize() {
        //some initialize
    }
    @Test
    public void waitPeriod() {
        long a = 1000*300; //wait 5 minutes
        if (getDatasetType().equals("BaseClass")) {
            a = 1000*60; // wait 1 minutes
        }
        try {
            Thread.sleep(a);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("waitPeriod " + getDatasetType());
    }

    @Test(dependsOnMethods = {"waitPeriod"})
    public void test() {
        log.info("test " + getDatasetType());
    }
}

public class DerivedClass extends BaseClass {
    @Override
    protected String getDatasetType() { return "DerivedClass"; }

}

如果TestNG中运行都class,最好1分钟后触发一次,只触发BaseClass的“测试”功能,5分钟后触发DerivedClass的“测试” “ 功能。但是在我的测试中运行,它在1分钟后触发了两个测试功能。

根据您的代码,您已在 BaseClass 中添加了 test() 方法。因此,当使用 @Test 注释调用方法时,getDatasetType() 将仅调用形式 BaseClass

如果你想达到预期的结果,我建议你在其他调用中分离出测试,将其称为测试类,并在 BaseClassDerivedClass

中保留实现

代码如下所示

  class BaseClass {
    protected String getDatasetType() {
        return "BaseClass";
    }
    public void initialize() {
        //some initialize
    }
    public void waitPeriod() {
        long a = 1000*300; //wait 5 minutes
        if (getDatasetType().equals("BaseClass")) {
            a = 1000*60; // wait 1 minutes
        }
        try {
            Thread.sleep(a);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("waitPeriod " + getDatasetType());
     }
  }


  public class DerivedClass extends BaseClass {
      @Override
      protected String getDatasetType() { return "DerivedClass"; }
  }

public class TestClass {
  BaseClass baseClass = new BaseClass();
  DerivedClass derivedClass  = new DerivedClass();

  @BeforeTest
  public void initialize() {
    baseClass.initialize();
  }
  @Test
  public void test_waitPeriod() {
    baseClass.waitPeriod();
  }
  @Test(dependsOnMethods = {"waitPeriod"})
  public void test_baseclass() {
    baseClass.test();
  }
  @Test(dependsOnMethods = {"waitPeriod"})
  public void test_derivedclass() {
    derivedClass.test();
  }
}

// other way can be
public class TestClass {
  BaseClass baseClass = new BaseClass();
  DerivedClass derivedClass  = new DerivedClass();

  @BeforeTest
  public void initialize() {
    baseClass.initialize();
  }

  @Test
  public void test_baseclass() {
    baseClass.waitPeriod();
    baseClass.test();
  }
  @Test
  public void test_derivedclass() {
    derivedClass.waitPeriod();
    derivedClass.test();
  }
}

这是伪代码。您可以根据您的要求对其进行改进,但请尝试将测试与主要实现分开。