如何使用selenium确认页面标题?

时间:2018-04-19 09:33:17

标签: java selenium selenium-webdriver automated-tests

      @Test(priority = 0)
      public void test() throws Exception {
        driver.get(baseUrl + "/");
        driver.findElement(By.name("email")).clear();
        driver.findElement(By.name("email")).sendKeys("lanka@ensiz.com");
        driver.findElement(By.name("password")).clear();
        driver.findElement(By.name("password")).sendKeys("123456");
        driver.findElement(By.xpath("//button[contains(text(),'Sign In')]")).click();

      }
      @Test(priority = 1)
      public void verifyHomepageTitle(){
              String expectedTitle = "Placer Admin - Home";
              String actualTitle = driver.getTitle();
              Assert.assertEquals(actualTitle, expectedTitle);     
      }
      @AfterClass(alwaysRun = true)
      public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
          fail(verificationErrorString);
        }
      }    

我是自动化测试的新手。我想确保有效的用户登录。因为我试图验证页面的标题。但我的测试一直都失败,因为它是在有效用户访问仪表板之前执行。我可以测试一下吗?我能否知道对此代码的正确修改?

请帮助..谢谢

2 个答案:

答案 0 :(得分:0)

您可以在仪表板页面上选择一个始终存在但不在登录页面上的元素。例如,菜单项或标题。

然后在登录测试结束时创建这样的等待,因此测试仅在加载仪表板后完成:

 WebDriverWait wait = new WebDriverWait(driver, 5);
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("XPath here")));

这将等待最多5秒钟以加载仪表板。当我在C#中做所有事情时,语法可能会出错。

答案 1 :(得分:0)

使用此代码,它在我的机器中正常工作:

public class User3806999 {

    WebDriver driver;
    WebDriverWait wait;

    @BeforeClass
    public void setUpClass(){
        System.setProperty("webdriver.chrome.driver", "F:\\Automation\\chromedriver.exe");
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver,30); 
        driver.manage().window().maximize();
        driver.get("https://test.admin.placer.life/login");
    }

    @Test()
    public void testLogin() throws Exception {
        driver.findElement(By.name("email")).clear();
        driver.findElement(By.name("email")).sendKeys("lanka@ensiz.com");
        driver.findElement(By.name("password")).clear();
        driver.findElement(By.name("password")).sendKeys("123456");
        driver.findElement(By.xpath("//button[contains(text(),'Sign In')]")).click();
        wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("user_menu"))));
        //Assert something here 
    }

    @Test(dependsOnMethods ={"testLogin"})
    public void verifyHomepageTitle(){
            String expectedTitle = "Placer Admin - Home";
            String actualTitle = driver.getTitle();
            Assert.assertEquals(actualTitle, expectedTitle);     
    }

    @AfterClass(alwaysRun = true)
    public void tearDown() throws Exception {
          //logout here 

      }
}