TestNG @Test attributes - dependOnMethods

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

in the above code, test1() will fail ---title of page doesn't contain string "Testing"---, but still test2() will continue to run, because there is no dependency,
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();
       }
}



Here, test2() will not execute as test1() failed, this just make sure we need to click on required link if the page title is Testing,
In the above code scenario, we are not on right page, so no need to click on selenium tutorial link.
  Same we have another attribute - dependsOnGroups

No comments:

Post a Comment