gpt4 book ai didi

JAVA - Selenium WebDriver - 断言和等待

转载 作者:行者123 更新时间:2023-11-30 05:40:39 25 4
gpt4 key购买 nike

我的断言有问题,或者更确切地说,断言执行的“时间”有问题。因此,断言正在正常工作,但是,它运行得太快,因为它正在执行而没有等待其应该加载的目标页面。这意味着断言未通过测试。

考虑到这一点,我尝试搜索如何向断言添加“等待”以使其在运行之前等待页面加载,但没有成功。

那么,有人可以帮忙解决这个问题吗?我该如何编码,以便断言“等待”页面加载然后执行?

我尝试将等待添加到 header 方法中,我尝试将等待添加到测试脚本中,但没有成功。

public class test1 extends DriverSetup{

//Here we are setting the method to use the homePage
private HomePage homePage = new HomePage(getDriver());

//Here we are setting the method logInPage
private AuthenticationPage authenticationPage = new AuthenticationPage(getDriver());

//Here are setting the method CreateAccountPage
private CreateAccountPage createAccountPage = new CreateAccountPage(getDriver());

//Here we are setting the method to access the Website HomePage with the driver
private void accessWebsiteHomePage (){

getDriver().get("http://automationpractice.com/index.php");
}

@Test
public void CreateAccount() {

accessWebsiteHomePage();

//Log in
homePage.logInBut();

//Authentication page "Create a new account" box
authenticationPage.setCreateAccountEmailAddress(emailGenerator.Email());
authenticationPage.CreateAccountButtonClick();

Assert.assertEquals("CREATE AN ACCOUNT", createAccountPage.HeaderCheckRightPage());

断言应该针对“CREATE AN ACCOUNT”页面,但它针对的是位于其之前的“AUTHENTICATION”页面,因此测试失败,因为打印的“实际”值是“AUTHENTICATION”页面,不是“创建帐户”页面。

最佳答案

您需要使用显式等待。这是一个等待标题等于某个内容的函数:

private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().equals(searchString);
}

您可以通过强制您想要匹配的内容的大小写来使其更加可靠,如下所示:

private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}

然后,您需要在断言之前添加以下内容:

WebDriverWait wait = new WebDriverWait(driver, 10, 100);
wait.until(titleIsEqualTo("CREATE AN ACCOUNT"));

我假设标题是指页面标题,因为您没有显示收集标题的代码。

*编辑*

上述 ExpectedCondition 的非 lambda 版本是:

private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
};
}

关于JAVA - Selenium WebDriver - 断言和等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55725083/

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