TestNG dependsOnMethods from different class

brayne picture brayne · Oct 7, 2011 · Viewed 28.6k times · Source

The dependsOnMethods attribute of the @Test annotation works fine when the test to be depended upon is in the same class as that of the test that has this annotation. But it does not work if the to-be-tested method and depended-upon method are in different classes. Example is as follows:

class c1 {
  @Test
  public void verifyConfig() {
    //verify some test config parameters
  }
}

class c2 {
  @Test(dependsOnMethods={"c1.verifyConfig"})
  public void dotest() {
    //Actual test
  }
}

Is there any way to get around this limitation? One easy way out is to create a test in class c2 that calls c1.verifyConfig(). But this would be too much repetition.

Answer

Cedric Beust picture Cedric Beust · Oct 8, 2011

Put the method in a group and use dependsOnGroups.

class c1 {
  @Test(groups={"c1.verifyConfig"})
  public void verifyConfig() {
    //verify some test config parameters
  }
}

class c2 {
  @Test(dependsOnGroups={"c1.verifyConfig"})
  public void dotest() {
    //Actual test
  }
}

It is recommended to verify configuration in a @Before* and throw if something goes wrong there so the tests won't run. This way the tests can focus on just testing.

class c2 {
  @BeforeClass
  public static void verifyConfig() {
    //verify some test config parameters
    //Usually just throw exceptions
    //Assert statements will work
  }

  @Test
  public void dotest() {
    //Actual test
  }
}