in testng dependonfunction如何处理继承

kd3sttzy  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(362)

假设我在下面定义了两个类baseclass和derivedclass。base的waitperiod为1分钟,Derivated的waitperiod为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中运行这两个类,最好在1分钟后运行一次,它将只触发基类的“test”函数,5分钟后,它将触发derivedclass的“test”函数。但是在我的测试运行中,它在1分钟后触发了两个测试函数。

zbwhf8kr

zbwhf8kr1#

根据您的代码,在中添加了test()方法 BaseClass . 所以当用@test注解调用方法时, getDatasetType() 将被称为形式 BaseClass 只是。
如果您想获得预期的结果,我建议您将其他调用中的测试分离出来,将其称为testclass,并将实现保留在中 BaseClass 以及 DerivedClass 代码如下所示

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();
  }
}

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

相关问题