我想测试我的LoginPage功能。 因此,如果我输入正确的用户名和密码,则我将被重定向到欢迎页面.jsp .
我使用了容器托管安全性,因此您将在 URL 中看到一些j_security_check。
Feature: MyApp Login Feature
Validate MyApp Login Features
Scenario Outline: User logs to MyApp
Given I navigate to MyApp login page
And I enter <username> and <password>
And I click on login button
Then user entered correct username and password then they should be redirected to the proper <url>
Examples:
| username | password | url |
| correctuser | correctpassword | welcome.jsp |
我的问题是如何处理 302 重定向。 如果我在浏览器中查看我的网络选项卡,我会看到以下序列
- 发布j_security_check
受到欢迎.jsp
@Then("^Then user entered correct username and password then they should be redirected to the proper ([^"]*)$") public void user_should_be_redirected_to_the_proper(String expectedURL) throws Throwable { System.out.println("expectedURL :: " + expectedURL ); if (driver.getCurrentUrl().contains(expectedURL)) { System.out.println("MyApp Test Pass"); } else { System.out.println("MyApp Test Failed"); Assert.fail("MyApp Test failed!"); } }
我在这里看到一些问题,比如 Selenium WebDriver 中的 JavaScript Executor
但我认为这不是一个 AJAX 调用,我们正在等待一个 DOM 就绪
尝试在断言之前使用以下ExpectedConditions
之一、urlMatches、urlContains、urlToBe,以等待重定向完成。
@Grasshopper的答案是正确的方向,你需要将WebDriverWait与ExpectConditions一起诱导。但是,由于您将使用expectedURL
而不是urlMatches,urlContains或urlToBe断言getCurrentUrl()
,因此您需要使用titleContains()
方法传递最终URL的页面标题参数。预期条件titleContains()
当标题与应用程序标题匹配时,它将返回 true。此转弯将确保您已设置最终网址。您可以使用以下代码块,我假设以welcome.jsp结尾的最终URL将具有页面标题为Welcome - Mark Estrada - 主页:
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
// other lines of code
@Then("^Then user entered correct username and password then they should be redirected to the proper ([^"]*)$")
public void user_should_be_redirected_to_the_proper(String expectedURL) throws Throwable
{
new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Welcome - Mark Estrada - Home Page"));
System.out.println("expectedURL :: " + expectedURL );
if (driver.getCurrentUrl().contains(expectedURL)) {
System.out.println("MyApp Test Pass");
} else {
System.out.println("MyApp Test Failed");
Assert.fail("MyApp Test failed!");
}
}
您可以等到 URL 包含或匹配某些字符串:
import org.openqa.selenium.support.ui.ExpectedConditions;
WebDriverWait wait5s = new WebDriverWait(driver,5);
wait5s.until(ExpectedConditions.urlContains("welcome.jsp"));
等待 DOM 加载更好,等待元素是可点击的:
wait5s.until(ExpectedConditions.elementToBeClickable(locator);
或可选:
wait5s.until(ExpectedConditions.attributeToBe(locator, attribute, value);
在错误的凭据情况下,只需与if/else