繁体   English   中英

在 Selenium Java 中测试时如何避免一次又一次登录

[英]How to avoid login again and again while testing in Selenium Java

我想自动化 web 应用程序。 每次运行测试时都需要登录。 我想绕过这个登录步骤,直接访问所需的 URL。 下面是我的代码,它不能按照我的需要工作。

class practice {

public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver;
ChromeOptions options = new ChromeOptions();


options.addArguments("--user-data-dir=C:/Users/hp/AppData/Local/Google/Chrome/User Data/Profile 1");
System.setProperty("webdriver.chrome.driver", "C:///chromedriver.exe");
driver=new ChromeDriver();

driver.get("https:xyz.com/dashboard/campaigns#display=active&page=1&view=list&sort=startdate&sort_order=desc&region=all&search=");

// If login page appears
if (driver.findElement(By.xpath("//*[@id='sessions_new']/div/div[2]/div[2]/div[2]/div/div[1]/h2")).isDisplayed())
{
System.out.println("This is login page");



driver.findElement(
    By.xpath("//*[@id=\"sessions_new\"]/div/div[2]/div[2]/div[2]/div/div[2]/div[2]/form/div/div[1]/input")).sendKeys(
    "wadfd@gmail.com");
driver.findElement(
    By.xpath("//*[@id=\"sessions_new\"]/div/div[2]/div[2]/div[2]/div/div[2]/div[2]/form/div/div[2]/input")).sendKeys(
    "abc123");
driver.findElement(By.name("login")).click();

}

// if required page appears
else
{
System.out.println("This is NOT login page");
driver.findElement(By.xpath("/html/body/div[2]/section[1]/nav/ul/li[2]/a/span")).click();
}

}

}

当我在下面看到您的代码时,有几件事可能导致 go 出错,因此很难告诉您要修复什么(它会崩溃吗?哪一行?),但是在您完成之后我看不到任何像.click()这样的交互sendKeys操作。 所以对我来说,它看起来像在if块中,当您在登录页面时,您填写您的凭据但从不按下登录按钮。

还有一点:你应该避免像 plage 一样使用Thread.sleep 尝试寻找wait.until(ExpectedConditions.visibilityOfElementLocated(<put here a selector for a element you want to see loaded>)); 或任何类似的预期条件,以便更清洁、更有效地使用 Selenium。

当您想减少登录时间并节省运行时间时,也许您可以尝试两种解决方案。

  1. 如果使用TestNG,只需在BeforeClass()中加入Login即可,这样class中的所有test()只需要Login一次。
  2. 如果 web 应用程序在 cookie 中保存登录验证信息,您可以手动登录并提取 cookie,然后经过一些格式转换后,您可以将 cookie 传递给驱动程序。 像这样的演示:
// Tip: firstly convert the raw cookie String to List<Cookie>, 
// then call the below in for-loop

driver.manage().addCookie(Cookie cookie);

但是,我认为,选项2在实际项目测试中并不是一个好的解决方案,仅供参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM