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

时间:2018-09-25 19:54:51

标签: java selenium testng

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

  }
}

1 个答案:

答案 0 :(得分:-1)

您可以使用通过声明(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("kasiatrzaska@o2.pl");
    WebElement SendButton = driver.findElement(sendButton);
    SendButton.click();
    WebElement ErrorField = driver.findElement(errorField);
    {
      Assert.assertEquals(ErrorField.getText(), "The message cannot be blank.");
    }    
  }

}