gpt4 book ai didi

java - 我如何使用 isElementPresent(By by) 方法来验证我的测试脚本是否正常工作?

转载 作者:行者123 更新时间:2023-11-29 03:33:13 28 4
gpt4 key购买 nike

如何使用此代码:

public boolean isElementPresent(By by)

当我导出我的测试脚本时,测试脚本中会自动出现,但下面的大部分方法都没有使用,所以会有警告说我没有使用那个方法..我的测试脚本将失败.

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class cheesecake {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();

@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.google.com.my/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testCheesecake() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("cheesecake");
driver.findElement(By.cssSelector("a.q.qs")).click();
driver.findElement(By.cssSelector("span.mn-dwn-arw")).click();
driver.findElement(By.xpath("//a[contains(text(),'News')]")).click();
}

@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}

private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}

我能知道这些方法有什么用,怎么用吗?因为,如果我删除它们,我的测试脚本可以运行,但即使输入错误的密码也可以登录系统。

最佳答案

你是对的,这是由 IDE 自动生成的,但你错误地编辑了它:

public boolean isElementPresent(By by) {
try {
driver.findElements(by);
return true;
} catch (org.openqa.selenium.NoSuchElementException e) {
return false;
}
}

然后调用它:

isElementPresent(By.id("J_idt16:J_idt30"));

它可以更容易地确定一个元素在页面上是否可见。有时您想拥有那个元素并用它做一些事情,有时您只想知道它是否存在。这是为了让这样做变得容易。

如果您的测试脚本有问题,请发布您正在使用的代码和您正在运行的 HTML,或者尝试在另一个面向公众的网站上重现它。

关于java - 我如何使用 isElementPresent(By by) 方法来验证我的测试脚本是否正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16912357/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com