There are situations when we want to run our tests depends on the prior test execution like
if a particular test is run fine, then execute this test or else skip the test execution…
Basically we are creating inter dependencies in test execution.
Examples
Launch browser with URL, verify if title matches, then login
In Gmail, if login successful, then verify if Inbox link present or not
If report generated, then print the report
Let’s see the code implementation
public class Dependonmethods { WebDriver driver; @Test public void test1() { driver = new FirefoxDriver(); driver.get("http:qavalidation.com"); Assert.assertTrue(driver.getTitle().contains("Testing")); } @Test public void test2() { driver.findElement(By.linkText("Selenium Tutorial!")).click(); } }
but we need to create a dependency to make sure test2() will run only if test1() runs successfully.
to achieve this, let’s implement dependsOnMethods
public class Dependonmethods { WebDriver driver; @Test public void test1() { driver = new FirefoxDriver(); driver.get("http:qavalidation.com"); Assert.assertTrue(driver.getTitle().contains("Testing")); } @Test(dependsOnMethods = {"test1"}) public void test2() { driver.findElement(By.linkText("Selenium Tutorial!")).click(); } }
In the above code scenario, we are not on right page, so no need to click on selenium tutorial link.
package testngdependon; import org.testng.annotations.Test; public class DependonGrps { @Test(groups ={"ab"}) public void method1(){ System.out.println(25/0);} @Test(dependsOnGroups = { "a.*" }) public void method2(){ System.out.println("tc2: testcase1");} @Test(groups ={"a"}) public void method3(){ System.out.println("tc3: testcase1");} @Test(groups ={"a"}) public void method4(){ System.out.println("tc4: testcase1");} }
OutPut –
tc3: testcase1
tc4: testcase1
PASSED: method3
PASSED: method4
FAILED: method1
java.lang.ArithmeticException: / by zero
at dependonMethods.Testcs1.method1(Testcs1.java:9)
…
SKIPPED: method2
NOTE : We can use regular expression, a.* refers to a and ab as well.
Short link – bit.ly/qav-testngdependon