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

i2loujxw  于 2022-11-24  发布在  Java
关注(0)|答案(1)|浏览(218)

我对自动化测试还是个新手。出于练习的目的,我想使用TestNG.This is the page在Selenium中为contact表单创建测试。我创建了几个测试用例,但我不确定如何声明稍后将调用的变量(在同一个类中)。代码如下,我想声明“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("kasiatrzaska@o2.pl");
    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.");
    }

  }
}
7gcisfzg

7gcisfzg1#

  • 您可以使用By declaration(POM Way),即一次声明,多次调用。它适用于同一个类,也适用于其他类。您可以通过Public声明在其他类中访问它。*
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("kasiatrzaska@o2.pl");
    WebElement SendButton = driver.findElement(sendButton);
    SendButton.click();
    WebElement ErrorField = driver.findElement(errorField);
    {
      Assert.assertEquals(ErrorField.getText(), "The message cannot be blank.");
    }    
  }

}

相关问题