1

我是 Java 新手,我正在使用 selenium 和 Junit 来自动化 Web 应用程序。我们的网站作为其预生产环境需要 5-8 秒才能加载,因此我在我的方法中使用了 Thread.sleep。我觉得这不是一个好的选择,因此需要一个代码来减慢自动化,并逐步控制执行流程。我也没有时间安装 testng 来使用隐式和显式等待。减慢方法的变量可以,但是如何?

4

1 回答 1

0

显式和隐式等待不是 TestNG 的 selenium 特性,testng 仅用作控制测试流程和断言的测试框架。

进口:

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

代码:

WebDriver driver = new ChromeDriver();

driver.get("https://google.com/ncr");

driver.findElement(By.name("q")).sendKeys("cheese" + Keys.ENTER);

   // Initialize and wait till element(link) became clickable - timeout in 10 seconds

WebElement firstResult = new WebDriverWait(driver, Duration.ofSeconds(10))
           .until(ExpectedConditions.elementToBeClickable(By.xpath("//a/h3")));

    // Print the first result
System.out.println(firstResult.getText());
于 2020-12-08T06:16:58.263 回答