如何使用TestNG/Selenium/Java声明全局变量?

问题描述 投票:0回答:1

我对自动化测试完全陌生。 出于练习目的,我想使用 TestNG 在 Selenium 中为联系表单创建测试。 这是我用于练习的页面。我创建了几个测试用例,但我不确定如何声明稍后将调用的变量(在同一个类中)。代码如下,我想声明“Email”、“ErrorField”和“SendButton” - 所有建议都非常感谢,因为我尝试了多种方法但遇到了错误。

public class FormValidation {
  protected static WebDriver driver;

  @BeforeTest()
  public void beforeTest() {
    System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
  }

  @Test(priority = 0)
  public void blankFormTest() {
    driver = new ChromeDriver();
    driver.get("http://automationpractice.com/index.php?controller=contact");

    WebElement SendButton = driver.findElement(By.id("submitMessage"));
    SendButton.click();
    WebElement ErrorField = driver.findElement(By.xpath("//*[@id=\"center_column\"]/div/ol/li"));
    {
      Assert.assertEquals(ErrorField.getText(), "Invalid email address.");

    }
  }

  @Test(priority = 1)
  public void correctEmailonly() {
    WebElement Email = driver.findElement(By.id("email"));
    Email.sendKeys("[email protected]");
    WebElement SendButton = driver.findElement(By.id("submitMessage"));
    SendButton.click();
    WebElement ErrorField = driver.findElement(By.xpath("//*[@id=\"center_column\"]/div/ol/li"));
    {
      Assert.assertEquals(ErrorField.getText(), "The message cannot be blank.");
    }

  }
}
java selenium testng
1个回答
0
投票

可以通过通过声明(POM方式)来实现,即声明一次,多次调用。它也适用于同一类别和其他类别。您可以通过公共声明在其他类中访问它。

public class FormValidation {
  protected static WebDriver driver;

  By errorField = By.xpath("//*[@id=\"center_column\"]/div/ol/li");
  By sendButton = By.id("submitMessage");
  By email = By.id("email");


  @BeforeTest()
  public void beforeTest() {
    System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
  }

  @Test(priority = 0)
  public void blankFormTest() {
    driver = new ChromeDriver();
    driver.get("http://automationpractice.com/index.php?controller=contact");

    WebElement SendButton = driver.findElement(sendButton);
    SendButton.click();
    WebElement ErrorField = driver.findElement(errorField);
    {
      Assert.assertEquals(ErrorField.getText(), "Invalid email address.");

    }
  }

  @Test(priority = 1)
  public void correctEmailonly() {
    WebElement Email = driver.findElement(email);
    Email.sendKeys("[email protected]");
    WebElement SendButton = driver.findElement(sendButton);
    SendButton.click();
    WebElement ErrorField = driver.findElement(errorField);
    {
      Assert.assertEquals(ErrorField.getText(), "The message cannot be blank.");
    }    
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.