Using dynamic locators in methods

Getting back to dynamic elements created during tests, how are they handled? We wouldn't want to define them upfront, and cannot possibly define them upfront, due to the nature of the dynamic names, text, or IDs associated with them.

So, let's build a method that takes a string parameter that defines some element in a page, which will get stuffed into an XPath locator on the fly. For this example, let's use a page's label elements.

To test all the //label elements in a web page—and in some cases, there can be dozens—we would want to store the labels in a data file and pass them into a test method one at a time, verifying that they exist on the page. To do this, we have to build the locator on the fly, as follows:

public void verifyLabel(String pattern,
String label
)
throws Exception {

WebDriver driver = CreateDriver.getInstance().getDriver();
String locator = "//label[contains(text(),'" + pattern + "')]";

assertEquals(
driver.findElement(By.xpath(locator)).getText(),
label);
}

That seems too easy to be true. In this example, we kept the locator in the page object class, kept a separation between that class and the test class calling the method, and created a dynamic locator to use instead of referencing a static locator from the page object class.

Let's look at one a little more complicated. In this next example, it wasn't enough to just reference a pattern to match label, but another control following the node as well:

public void verifyLabel(String pattern,
String label
)
throws Exception {

WebDriver driver = CreateDriver.getInstance().getDriver();
String locator = "//label[contains(text(),'" + pattern +
"')]/following::div[@class='help-text']";


assertEquals(driver.findElement(By.xpath(locator)).getText(),
label);
}

Those are some cases where the element is predictable. How about situations where you have no text to pass into the element locator? A good example might be a case where the application throws up multiple cascading error dialog boxes when an exception occurs; how would you handle that? Here is a simple method to build a locator on the fly for an unpredictable element, that being a set of dialogs, and it uses an index as part of the locator:

public void cleanup() {
String locator = "(//i[@class='icon-close'])[";
WebDriver driver = CreateDriver.getInstance().getDriver();

for ( int i = 10; i > 0; i-- ) {
try {
WebElement element =
driver.findElement(By.xpath(locator + i + "])"));

if ( BrowserUtils.elementExists(element, 0) ) {
element.click();
waitForGone(By.xpath(locator + i + "]"), 1);
}
}

catch(Exception e) {
// do nothing, just trap it...
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.187.121