首页 > 解决方案 > Selenium Java 测试等待重定向完成

问题描述

假设我想测试我的 LoginPage 功能。因此,如果我输入正确的用户名和密码,那么我将被重定向到 welcomepage.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 重定向。如果我在浏览器中查看我的网络选项卡,我会看到以下序列

  1. POST j_security_check
  2. 获取欢迎.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 Ready

标签: javaseleniumselenium-webdrivercucumberselenium-chromedriver

解决方案


您可以等到 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.


推荐阅读