简体   繁体   中英

Selenium Webdriver: How to verify that the required webpage is loaded

I am using Selenium Webdriver to automate tests for a website. After every event I want to verify if the action was successful or not. What is the best way to do it. Eg, How do I verify that correct webpage is loaded when a user clicks the SignIn button? One thing that I am doing right now is to get the source of the resulting page and look for specific words in that page for confirmation. If those words are there, I assume that the page is indeed loaded. But I dont think it is a nice way to go about.

If you are using Selenium Webdriver, you can obviously use WebDriver.findElement(By locator) to check if a certain object that is only going to be in the page you are waiting for. For Example, to check if login is successful, you can verify if "Logout" object is there in the page or not.

You don't have to take the source and check for required text. If the id for Logout button is "Logout" below line works for you...

assertTrue(driver.findElements(By.id("Logout").length > 0);

You should be testing general functionality, not that styling, etc. is correct. The advantage of automatic tests over manual ones is that it's really easy to test things with a wide variety of different data and that it is fast to rerun them after changes. Generally you are making the assumption that pages are looking about correct and you just want to test your program logic in a multitude of different situations.

For instance, if you sign in, check that the user appears as signed in and that let's say front page is shown correctly (via some text that only appears in a certain place on front page). Or if you have a multiple page form, where user is entering all sorts of data, check that the summary page lists everything correctly.

Don't check grab the entire source and parse it, rather you ought to use something like:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

import org.junit.*;

public class LoginTest extends WebDriverTest /* This would be your own superclass, from which you inherit the WebDriver instance. */ {
  private User user = new User();

  @Before
  public void setUp() {
    user.setName("Test Tommy");
    user.setPassword("foobar");
  }

  @Test
  public void userNameShouldBeShownAfterLogin() {
    // Go to your page and do the login, then wait for page load.

    String userNameOnPage = driver.findElement(By.id("usernameAfterLogin"));
    assertThat(userNameOnPage, is(equalTo(user.getName())));
  }
}

Page objects design pattern would be an ideal candidate for your requirement. It all gives other benefits. Refer this link https://code.google.com/p/selenium/wiki/PageObjects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM