需要使用 TestNG 在 java class 中循环

Need loop within the java class using TestNG

如果我有一个方法,我已经写了一个 for 循环,但是如果我的 TestNG 脚本中有多个方法怎么办。

如果我在 public class 中放置一个变量,我就能让它工作,但我需要这个 运行 hostnum 2 到 hostnum 50。所以我需要一个使用 TESTNG 时 class 中的 for 循环因此不能使用 public static main.

这是我的代码,请告诉我我能做什么。我是菜鸟:(

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

使用您 testng.xml 中的参数并将它们传递给您的测试。

你的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 -->

你的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);
  }

}