Max Smith
Max Smith

Reputation: 65

Need loop within the java class using TestNG

I already wrote a for loop if I have one method, but what if I have multiple method in my TestNG scripts.

I was able to make it work if I put a variable within the public class, but I need this to run hostnum 2 through hostnum 50. So I need a for loop within the class while using TESTNG so therefore can't use public static main.

here is my code please advise me what I can do. I'm a noob :(

    package firsttestngpackage;

import org.openqa.selenium.*;
import org.testng.annotations.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class Test5 {

    WebDriver driver;

    //I NEED A FOR LOOP WITHIN THIS CLASS!!






    //THIS IS NOT WORKING
/*  for {

    }
    int hostnum = x;*/

    //THIS IS NOT WORKING
/*  for (int x = 1; x <= 2; x++){
        int hostnum = x;
    }*/

    //THIS IS WORKING BUT NO LOOP :(
    int hostnum = 2;

    @Test(priority = 1, enabled = true)
    public void method1() throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com");
    }

    @Test(priority = 2, enabled = true)
    public void method2() throws Exception {
        driver.findElement(By.id("lst-ib")).sendKeys("host" + hostnum + "_CR");
    }
}

Upvotes: 2

Views: 2568

Answers (1)

peetya
peetya

Reputation: 3628

Use Parameters from your testng.xml and pass them to your tests.

Your testng.xml:

<suite name="TestSuite">
    <test name="Test2">
        <parameter name="host" value="host2_CR" />
        <classes>
            <class name="SampleTest" />
        </classes>
    </test> <!-- Test2 -->
    <test name="Test3">
        <parameter name="host" value="host3_CR" />
        <classes>
            <class name="SampleTest" />
        </classes>
    </test> <!-- Test3 -->
    <!-- ... -->
    <test name="Test50">
        <parameter name="host" value="host50_CR" />
        <classes>
            <class name="SampleTest" />
        </classes>
    </test> <!-- Test50 -->
</suite> <!-- TestSuite -->

Your class:

public class SampleTest {

  WebDriver driver;
  String host;

  @Parameters({"host"})
  @BeforeTest
  public void beforeTest(String host) {
    this.host = host;
  }

  @Test(priority = 1, enabled = true)
  public void method1() throws Exception {
    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.get("https://www.google.com");
  }

  @Test(priority = 2, enabled = true)
  public void method2() throws Exception {
    driver.findElement(By.id("lst-ib")).sendKeys(this.host);
  }

}

Upvotes: 1

Related Questions